forked from raspberrypi/picotool
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.cpp
2374 lines (2176 loc) · 94.9 KB
/
main.cpp
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
/*
* Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifdef _WIN32
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "cli.h"
#include "clipp/clipp.h"
#include <csignal>
#include <cstdio>
#include <map>
#include <iostream>
#include <vector>
#include <set>
#include <array>
#include <cstring>
#include <cstdarg>
#include <algorithm>
#include <iomanip>
#include <numeric>
#include <memory>
#include <functional>
#include <ctime>
#include "boot/uf2.h"
#include "picoboot_connection_cxx.h"
#include "pico/binary_info.h"
#include "pico/stdio_usb/reset_interface.h"
#include "elf.h"
#if defined(__unix__) || defined(__APPLE__)
#include <unistd.h>
#endif
// tsk namespace is polluted on windows
#ifdef _WIN32
#undef min
#undef max
#define _CRT_SECURE_NO_WARNINGS
#undef ERROR_CANCELLED
#endif
#define ERROR_ARGS -1
#define ERROR_FORMAT -2
#define ERROR_INCOMPATIBLE -3
#define ERROR_READ_FAILED -4
#define ERROR_WRITE_FAILED -5
#define ERROR_USB -6
#define ERROR_NO_DEVICE -7
#define ERROR_NOT_POSSIBLE -8
#define ERROR_CONNECTION -9
#define ERROR_CANCELLED -10
#define ERROR_VERIFICATION_FAILED -11
#define ERROR_UNKNOWN -99
using std::string;
using std::vector;
using std::pair;
using std::map;
typedef map<enum picoboot_device_result,vector<pair<libusb_device *, libusb_device_handle *>>> device_map;
typedef unsigned int uint;
auto memory_names = map<enum memory_type, string>{
{memory_type::sram, "RAM"},
{memory_type::sram_unstriped, "Unstriped RAM"},
{memory_type::flash, "Flash"},
{memory_type::xip_sram, "XIP RAM"},
{memory_type::rom, "ROM"}
};
static string tool_name = "picotool";
static string hex_string(int value, int width=8, bool prefix=true) {
std::stringstream ss;
if (prefix) ss << "0x";
ss << std::setfill('0') << std::setw(width) << std::hex << value;
return ss.str();
}
std::array<std::array<string, 30>, 10> pin_functions{{
{"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""},
{"SPI0 RX", "SPI0 CSn", "SPI0 SCK", "SPI0 TX", "SPI0 RX", "SPI0 CSn", "SPI0 SCK", "SPI0 TX", "SPI1 RX", "SPI1 CSn", "SPI1 SCK", "SPI1 TX", "SPI1 RX", "SPI1 CSn", "SPI1 SCK", "SPI1 TX", "SPI0 RX", "SPI0 CSn", "SPI0 SCK", "SPI0 TX", "SPI0 RX", "SPI0 CSn", "SPI0 SCK", "SPI0 TX", "SPI1 RX", "SPI1 CSn", "SPI1 SCK", "SPI1 TX", "SPI1 RX", "SPI1 CSn"},
{"UART0 TX", "UART0 RX", "UART0 CTS", "UART0 RTS", "UART1 TX", "UART1 RX", "UART1 CTS", "UART1 RTS", "UART1 TX", "UART1 RX", "UART1 CTS", "UART1 RTS", "UART0 TX", "UART0 RX", "UART0 CTS", "UART0 RTS", "UART0 TX", "UART0 RX", "UART0 CTS", "UART0 RTS", "UART1 TX", "UART1 RX", "UART1 CTS", "UART1 RTS", "UART1 TX", "UART1 RX", "UART1 CTS", "UART1 RTS", "UART0 TX", "UART0 RX"},
{"I2C0 SDA", "I2C0 SCL", "I2C1 SDA", "I2C1 SCL", "I2C0 SDA", "I2C0 SCL", "I2C1 SDA", "I2C1 SCL", "I2C0 SDA", "I2C0 SCL", "I2C1 SDA", "I2C1 SCL", "I2C0 SDA", "I2C0 SCL", "I2C1 SDA", "I2C1 SCL", "I2C0 SDA", "I2C0 SCL", "I2C1 SDA", "I2C1 SCL", "I2C0 SDA", "I2C0 SCL", "I2C1 SDA", "I2C1 SCL", "I2C0 SDA", "I2C0 SCL", "I2C1 SDA", "I2C1 SCL", "I2C0 SDA", "I2C0 SCL"},
{"PWM0 A", "PWM0 B", "PWM1 A", "PWM1 B", "PWM2 A", "PWM2 B", "PWM3 A", "PWM3 B", "PWM4 A", "PWM4 B", "PWM5 A", "PWM5 B", "PWM6 A", "PWM6 B", "PWM7 A", "PWM7 B", "PWM0 A", "PWM0 B", "PWM1 A", "PWM1 B", "PWM2 A", "PWM2 B", "PWM3 A", "PWM3 B", "PWM4 A", "PWM4 B", "PWM5 A", "PWM5 B", "PWM6 A", "PWM6 B"},
{"SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO", "SIO"},
{"PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0", "PIO0"},
{"PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1", "PIO1"},
{"","","","","","","","","","","","","","","","","","","","","CLOCK GPIN0","CLOCK GPOUT0","CLOCK GPIN1","CLOCK GPOUT1","CLOCK GPOUT2","CLOCK GPOUT3","","","",""},
{"USB OVCUR DET", "USB VBUS DET", "USB VBUS EN", "USB OVCUR DET", "USB VBUS DET", "USB VBUS EN", "USB OVCUR DET", "USB VBUS DET", "USB VBUS EN", "USB OVCUR DET", "USB VBUS DET", "USB VBUS EN", "USB OVCUR DET", "USB VBUS DET", "USB VBUS EN", "USB OVCUR DET", "USB VBUS DET", "USB VBUS EN", "USB OVCUR DET", "USB VBUS DET", "USB VBUS EN", "USB OVCUR DET", "USB VBUS DET", "USB VBUS EN", "USB OVCUR DET", "USB VBUS DET", "USB VBUS EN", "USB OVCUR DET", "USB VBUS DET", "USB VBUS EN"},
}};
auto bus_device_string = [](struct libusb_device *device) {
return string("Device at bus ") + std::to_string(libusb_get_bus_number(device)) + ", address " + std::to_string(libusb_get_device_address(device));
};
enum class filetype {bin, elf, uf2};
struct command_failure : std::exception {
command_failure(int code, string s) : c(code), s(std::move(s)) {}
const char *what() const noexcept override {
return s.c_str();
}
int code() const { return c; }
private:
int c;
string s;
};
struct cancelled_exception : std::exception { };
struct not_mapped_exception : std::exception {
const char *what() const noexcept override {
return "Hmm uncaught not mapped";
}
};
// from -> to
struct range {
range() : from(0), to(0) {}
range(uint32_t from, uint32_t to) : from(from), to(to) {}
uint32_t from;
uint32_t to;
bool empty() const {
return from >= to;
}
bool contains(uint32_t addr) const { return addr>=from && addr<to; }
uint32_t clamp(uint32_t addr) const {
if (addr < from) addr = from;
if (addr > to) addr = to;
return addr;
}
void intersect(const range& other) {
from = other.clamp(from);
to = other.clamp(to);
}
bool intersects(const range& other) const {
return !(other.from >= to || other.to < from);
}
};
static void __noreturn fail(int code, string msg) {
throw command_failure(code, std::move(msg));
}
static void __noreturn fail(int code, const char *format, ...) {
va_list args;
va_start(args, format);
static char error_msg[512];
vsnprintf(error_msg, sizeof(error_msg), format, args);
va_end(args);
fail(code, string(error_msg));
}
// ranges should not overlap
template <typename T> struct range_map {
struct mapping {
mapping(uint32_t offset, uint32_t max_offset) : offset(offset), max_offset(max_offset) {}
const uint32_t offset;
const uint32_t max_offset;
};
void insert(const range& r, T t) {
if (r.to != r.from) {
assert(r.to > r.from);
// check we don't overlap any existing map entries
auto f = m.upper_bound(r.from); // first element that starts after r.from
if (f != m.begin()) f--; // back up, to catch element that starts on or before r.from
for(; f != m.end() && f->first < r.to; f++) { // loop till we can't possibly overlap
range r2(f->first, f->second.first);
if (r2.intersects(r)) {
fail(ERROR_FORMAT, "Found overlapping memory ranges 0x%08x->0x%08x and 0x%08x->%08x\n",
r.from, r.to, r2.from, r2.to);
}
}
m.insert(std::make_pair(r.from, std::make_pair(r.to, t)));
}
}
pair<mapping, T> get(uint32_t p) {
auto f = m.upper_bound(p);
if (f == m.end()) {
if (m.empty())
throw not_mapped_exception();
} else if (f == m.begin()) {
throw not_mapped_exception();
}
f--;
assert(p >= f->first);
if (p >= f->second.first) {
throw not_mapped_exception();
}
return std::make_pair(mapping(p - f->first, f->second.first - f->first), f->second.second);
}
uint32_t next(uint32_t p) {
auto f = m.upper_bound(p);
if (f == m.end()) {
return std::numeric_limits<uint32_t>::max();
}
return f->first;
}
vector<range> ranges() {
vector<range> r;
r.reserve(m.size());
for(const auto &e : m) {
r.emplace_back(range(e.first, e.second.first));
}
return r;
}
size_t size() const { return m.size(); }
private:
map<uint32_t, pair<uint32_t, T>> m;
};
using cli::group;
using cli::option;
using cli::integer;
using cli::hex;
using cli::value;
struct cmd {
explicit cmd(string name) : _name(std::move(name)) {}
enum device_support { none, one, zero_or_more };
virtual group get_cli() = 0;
virtual string get_doc() const = 0;
virtual device_support get_device_support() { return one; }
virtual bool force_requires_pre_reboot() { return true; }
// return true if the command caused a reboot
virtual bool execute(device_map& devices) = 0;
const string& name() { return _name; }
private:
string _name;
};
struct _settings {
string filename;
string file_type;
uint32_t binary_start = FLASH_START;
int bus=-1;
int address=-1;
uint32_t offset = 0;
uint32_t from = 0;
uint32_t to = 0;
bool offset_set = false;
bool range_set = false;
bool reboot_usb = false;
bool reboot_app_specified = false;
bool force = false;
bool force_no_reboot = false;
struct {
bool show_basic = false;
bool all = false;
bool show_pins = false;
bool show_device = false;
bool show_build = false;
} info;
struct {
bool verify = false;
bool execute = false;
bool no_overwrite = false;
bool no_overwrite_force = false;
bool update = false;
} load;
struct {
bool all = false;
} save;
struct {
bool semantic = false;
} version;
};
_settings settings;
std::shared_ptr<cmd> selected_cmd;
auto device_selection =
(
(option("--bus") & integer("bus").min_value(0).max_value(255).set(settings.bus)
.if_missing([] { return "missing bus number"; })) % "Filter devices by USB bus number" +
(option("--address") & integer("addr").min_value(1).max_value(127).set(settings.address)
.if_missing([] { return "missing address"; })) % "Filter devices by USB device address"
#if !defined(_WIN32)
+ option('f', "--force").set(settings.force) % "Force a device not in BOOTSEL mode but running compatible code to reset so the command can be executed. After executing the command (unless the command itself is a 'reboot') the device will be rebooted back to application mode" +
option('F', "--force-no-reboot").set(settings.force_no_reboot) % "Force a device not in BOOTSEL mode but running compatible code to reset so the command can be executed. After executing the command (unless the command itself is a 'reboot') the device will be left connected and accessible to picotool, but without the RPI-RP2 drive mounted"
#endif
).min(0).doc_non_optional(true);
auto file_types = (option ('t', "--type") & value("type").set(settings.file_type))
% "Specify file type (uf2 | elf | bin) explicitly, ignoring file extension";
auto file_selection =
(
value("filename").with_exclusion_filter([](const string &value) {
return value.find_first_of('-') == 0;
}).set(settings.filename) % "The file name" +
file_types
);
struct info_command : public cmd {
info_command() : cmd("info") {}
bool execute(device_map& devices) override;
device_support get_device_support() override {
if (settings.filename.empty())
return zero_or_more;
else
return none;
}
group get_cli() override {
return (
(
option('b', "--basic").set(settings.info.show_basic) % "Include basic information. This is the default" +
option('p', "--pins").set(settings.info.show_pins) % "Include pin information" +
option('d', "--device").set(settings.info.show_device) % "Include device information" +
option('l', "--build").set(settings.info.show_build) % "Include build attributes" +
option('a', "--all").set(settings.info.all) % "Include all information"
).min(0).doc_non_optional(true) % "Information to display" +
(
device_selection % "To target one or more connected RP2040 device(s) in BOOTSEL mode (the default)" |
file_selection % "To target a file"
).major_group("TARGET SELECTION").min(0).doc_non_optional(true)
);
}
string get_doc() const override {
return "Display information from the target device(s) or file.\nWithout any arguments, this will display basic information for all connected RP2040 devices in BOOTSEL mode";
}
};
struct verify_command : public cmd {
verify_command() : cmd("verify") {}
bool execute(device_map &devices) override;
group get_cli() override {
return (
device_selection % "Target device selection" +
file_selection % "The file to compare against" +
(
(option('r', "--range").set(settings.range_set) % "Compare a sub range of memory only" &
hex("from").set(settings.from) % "The lower address bound in hex" &
hex("to").set(settings.to) % "The upper address bound in hex").force_expand_help(true) +
(option('o', "--offset").set(settings.offset_set) % "Specify the load address when comparing with a BIN file" &
hex("offset").set(settings.offset) % "Load offset (memory address; default 0x10000000)").force_expand_help(true)
).min(0).doc_non_optional(true) % "Address options"
);
}
string get_doc() const override {
return "Check that the device contents match those in the file.";
}
};
struct save_command : public cmd {
save_command() : cmd("save") {}
bool execute(device_map &devices) override;
group get_cli() override {
return (
(
option('p', "--program") % "Save the installed program only. This is the default" |
option('a', "--all").doc_non_optional(true).set(settings.save.all) % "Save all of flash memory" |
(
option('r', "--range").set(settings.range_set) % "Save a range of memory. Note that UF2s always store complete 256 byte-aligned blocks of 256 bytes, and the range is expanded accordingly" &
hex("from").set(settings.from) % "The lower address bound in hex" &
hex("to").set(settings.to) % "The upper address bound in hex"
).min(0).doc_non_optional(true)
).min(0).doc_non_optional(true).no_match_beats_error(false) % "Selection of data to save" +
( // note this parenthesis seems to help with error messages for say save --foo
device_selection % "Source device selection" +
file_selection % "File to save to"
)
);
}
string get_doc() const override {
return "Save the program / memory stored in flash on the device to a file.";
}
};
struct load_command : public cmd {
load_command() : cmd("load") {}
bool execute(device_map &devices) override;
group get_cli() override {
return (
(
option('n', "--no-overwrite").set(settings.load.no_overwrite) % "When writing flash data, do not overwrite an existing program in flash. If picotool cannot determine the size/presence of the program in flash, the command fails" +
option('N', "--no-overwrite-unsafe").set(settings.load.no_overwrite_force) % "When writing flash data, do not overwrite an existing program in flash. If picotool cannot determine the size/presence of the program in flash, the load continues anyway" +
option('u', "--update").set(settings.load.update) % "Skip writing flash sectors that already contain identical data" +
option('v', "--verify").set(settings.load.verify) % "Verify the data was written correctly" +
option('x', "--execute").set(settings.load.execute) % "Attempt to execute the downloaded file as a program after the load"
).min(0).doc_non_optional(true) % "Post load actions" +
file_selection % "File to load from" +
(
option('o', "--offset").set(settings.offset_set) % "Specify the load address for a BIN file" &
hex("offset").set(settings.offset) % "Load offset (memory address; default 0x10000000)"
).force_expand_help(true) % "BIN file options" +
device_selection % "Target device selection"
);
}
string get_doc() const override {
return "Load the program / memory range stored in a file onto the device.";
}
};
struct help_command : public cmd {
help_command() : cmd("help") {}
bool execute(device_map &devices) override;
device_support get_device_support() override {
return device_support::none;
}
group get_cli() override {
return group(
value("cmd").min(0) % "The command to get help for"
);
}
string get_doc() const override {
return "Show general help or help for a specific command";
}
};
struct version_command : public cmd {
version_command() : cmd("version") {}
bool execute(device_map &devices) override {
if (settings.version.semantic)
std::cout << PICOTOOL_VERSION << "\n";
else
std::cout << "picotool v" << PICOTOOL_VERSION << " (" << SYSTEM_VERSION << ", " << COMPILER_INFO << ")\n";
return false;
}
device_support get_device_support() override {
return device_support::none;
}
group get_cli() override {
return group(
option('s', "--semantic").set(settings.version.semantic) % "Output semantic version number only"
);
}
string get_doc() const override {
return "Display picotool version";
}
};
struct reboot_command : public cmd {
bool quiet;
reboot_command() : cmd("reboot") {}
bool execute(device_map &devices) override;
group get_cli() override {
return
(
option('a', "--application").set(settings.reboot_app_specified) % "Reboot back into the application (this is the default)" +
option('u', "--usb").set(settings.reboot_usb) % "Reboot back into BOOTSEL mode "
#if defined(_WIN32)
+ option('f', "--force").set(settings.force) % "Force a device not in BOOTSEL mode but running compatible code to reboot."
#endif
).min(0).doc_non_optional(true) % "Reboot type" +
device_selection % "Selecting the device to reboot";
}
bool force_requires_pre_reboot() override {
// no point in rebooting twice
return false;
}
string get_doc() const override {
return "Reboot the device";
}
} reboot_cmd;
vector<std::shared_ptr<cmd>> commands {
std::shared_ptr<cmd>(new info_command()),
std::shared_ptr<cmd>(new load_command()),
std::shared_ptr<cmd>(new save_command()),
std::shared_ptr<cmd>(new verify_command()),
std::shared_ptr<cmd>(new reboot_command()),
std::shared_ptr<cmd>(new version_command()),
std::shared_ptr<cmd>(new help_command()),
};
template <typename T>
std::basic_string<T> lowercase(const std::basic_string<T>& s)
{
std::basic_string<T> s2 = s;
std::transform(s2.begin(), s2.end(), s2.begin(), tolower);
return std::move(s2);
}
template <typename T>
std::basic_string<T> uppercase(const std::basic_string<T>& s)
{
std::basic_string<T> s2 = s;
std::transform(s2.begin(), s2.end(), s2.begin(), toupper);
return std::move(s2);
}
clipp::formatting_ostream<std::ostream> fos(std::cout);
static void sleep_ms(int ms) {
#if defined(__unix__) || defined(__APPLE__)
usleep(ms * 1000);
#else
Sleep(ms);
#endif
}
using cli::option;
using cli::integer;
int parse(const int argc, char **argv) {
bool help_mode = false;
bool no_global_header = false;
bool no_synopsis = false;
int tab = 4;
bool first = true;
auto section_header=[&](const string &name) {
fos.first_column(0);
fos.hanging_indent(0);
if (!first) fos.wrap_hard();
first = false;
fos << (uppercase(name) + ":\n");
};
auto usage=[&]() {
if (help_mode && selected_cmd) {
section_header(selected_cmd->name());
fos.first_column(tab);
fos << selected_cmd->get_doc() << "\n";
} else if (!selected_cmd && !no_global_header) {
section_header(tool_name);
fos.first_column(tab);
fos << "Tool for interacting with a RP2040 device in BOOTSEL mode, or with a RP2040 binary" << "\n";
}
vector<string> synopsis;
for(auto &c : commands) {
if (selected_cmd && c != selected_cmd) continue;
vector<string> cmd_synposis = c->get_cli().synopsys();
for(auto &s : cmd_synposis) {
synopsis.push_back(c->name()+" "+s);
}
}
if (!no_synopsis) {
section_header("SYNOPSIS");
for (auto &s : synopsis) {
fos.first_column(tab);
fos.hanging_indent((int)tool_name.length() + tab);
fos << (tool_name + " ").append(s).append("\n");
}
}
if (!selected_cmd) {
section_header("COMMANDS");
size_t max = 0;
for (auto &cmd : commands) {
max = std::max(cmd->name().size(), max);
}
for (auto &cmd : commands) {
fos.first_column(tab);
fos << cmd->name();
fos.first_column((int)(max + tab + 3));
std::stringstream s;
s << cmd->get_doc();
s << "\n";
fos << s.str();
}
} else if (!help_mode) {
fos.first_column(0);
fos.hanging_indent(0);
fos.wrap_hard();
fos << string("Use \"picotool help ").append(selected_cmd->name()).append("\" for more info\n");
} else {
cli::option_map options;
selected_cmd->get_cli().get_option_help("", "", options);
for (const auto &major : options.contents.ordered_keys()) {
section_header(major.empty() ? "OPTIONS" : major);
for (const auto &minor : options.contents[major].ordered_keys()) {
if (!minor.empty()) {
fos.first_column(tab);
fos.hanging_indent(tab*2);
fos << minor << "\n";
}
for (const auto &opts : options.contents[major][minor]) {
fos.first_column(tab*2);
fos.hanging_indent(0);
fos << opts.first << "\n";
fos.first_column(tab*3);
fos.hanging_indent(0);
fos << opts.second << "\n";
}
}
}
}
if (!selected_cmd) {
fos.first_column(0);
fos.hanging_indent(0);
fos.wrap_hard();
fos << "Use \"picotool help <cmd>\" for more info\n";
}
fos.flush();
};
auto args = cli::make_args(argc, argv);
if (args.empty()) {
usage();
return 0;
}
auto find_command = [&](const string& name) {
if (name[0]=='-') {
no_global_header = true;
throw cli::parse_error("Expected command name before any options");
}
auto cmd = std::find_if(commands.begin(), commands.end(), [&](auto &x) { return x->name() == name; });
if (cmd == commands.end()) {
selected_cmd = nullptr; // we want to list all commands
no_synopsis = true;
no_global_header = true;
throw cli::parse_error("Unknown command: " + name);
}
return *cmd;
};
try {
selected_cmd = find_command(args[0]);
if (selected_cmd->name() == "help") {
help_mode = true;
if (args.size() == 1) {
selected_cmd = nullptr;
usage();
return 0;
} else {
selected_cmd = find_command((args[1]));
usage();
selected_cmd = nullptr;
return 0;
}
} else if (!selected_cmd) {
no_synopsis = true;
no_global_header = true;
throw cli::parse_error("unknown command '" + args[0] + "'");
}
args.erase(args.begin()); // remove the cmd itself
cli::match(settings, selected_cmd->get_cli(), args);
} catch (std::exception &e) {
fos.wrap_hard();
fos << "ERROR: " << e.what() << "\n\n";
usage();
return ERROR_ARGS;
}
return 0;
}
template <typename T> struct raw_type_mapping {
};
#define SAFE_MAPPING(type) template<> struct raw_type_mapping<type> { typedef type access_type; }
//template<> struct raw_type_mapping<uint32_t> {
// typedef uint32_t access_type;
//};
// these types may be filled directly from byte representation
SAFE_MAPPING(uint8_t);
SAFE_MAPPING(char);
SAFE_MAPPING(uint16_t);
SAFE_MAPPING(uint32_t);
SAFE_MAPPING(binary_info_core_t);
SAFE_MAPPING(binary_info_id_and_int_t);
SAFE_MAPPING(binary_info_id_and_string_t);
SAFE_MAPPING(binary_info_block_device_t);
SAFE_MAPPING(binary_info_pins_with_func_t);
SAFE_MAPPING(binary_info_pins_with_name_t);
SAFE_MAPPING(binary_info_named_group_t);
#define BOOTROM_MAGIC 0x01754d
#define BOOTROM_MAGIC_ADDR 0x00000010
static inline uint32_t rom_table_code(char c1, char c2) {
return (c2 << 8u) | c1;
}
struct memory_access {
virtual void read(uint32_t p, uint8_t *buffer, uint size) {
read(p, buffer, size, false);
}
virtual void read(uint32_t, uint8_t *buffer, uint size, bool zero_fill) = 0;
virtual bool is_device() { return false; }
virtual uint32_t get_binary_start() = 0;
uint32_t read_int(uint32_t addr) {
assert(!(addr & 3u));
uint32_t rc;
read(addr, (uint8_t *)&rc, 4);
return rc;
}
uint32_t read_short(uint32_t addr) {
assert(!(addr & 1u));
uint16_t rc;
read(addr, (uint8_t *)&rc, 2);
return rc;
}
// read a vector of types that have a raw_type_mapping
template <typename T> void read_raw(uint32_t addr, T &v) {
typename raw_type_mapping<T>::access_type& check = v; // ugly check that we aren't trying to read into something we shouldn't
read(addr, (uint8_t *)&v, sizeof(typename raw_type_mapping<T>::access_type));
}
// read a vector of types that have a raw_type_mapping
template <typename T> vector<T> read_vector(uint32_t addr, uint count, bool zero_fill = false) {
assert(count);
vector<typename raw_type_mapping<T>::access_type> buffer(count);
read(addr, (uint8_t *)buffer.data(), count * sizeof(typename raw_type_mapping<T>::access_type), zero_fill);
vector<T> v;
v.reserve(count);
for(const auto &e : buffer) {
v.push_back(e);
}
return v;
}
template <typename T> void read_into_vector(uint32_t addr, uint count, vector<T> &v, bool zero_fill = false) {
vector<typename raw_type_mapping<T>::access_type> buffer(count);
if (count) read(addr, (uint8_t *)buffer.data(), count * sizeof(typename raw_type_mapping<T>::access_type), zero_fill);
v.clear();
v.reserve(count);
for(const auto &e : buffer) {
v.push_back(e);
}
}
};
uint32_t bootrom_func_lookup(memory_access& access, uint16_t tag) {
auto magic = access.read_int(BOOTROM_MAGIC_ADDR);
magic &= 0xffffff; // ignore bootrom version
if (magic != BOOTROM_MAGIC) {
if (!((magic ^ BOOTROM_MAGIC)&0xffff))
fail(ERROR_INCOMPATIBLE, "Incorrect RP2040 BOOT ROM version");
else
fail(ERROR_INCOMPATIBLE, "RP2040 BOOT ROM not found");
}
// dereference the table pointer
uint32_t table_entry = access.read_short(BOOTROM_MAGIC_ADDR + 4);
uint16_t entry_tag;
do {
entry_tag = access.read_short(table_entry);
if (entry_tag == tag) {
// 16 bit symbol is next
return access.read_short(table_entry+2);
}
table_entry += 4;
} while (entry_tag);
fail(ERROR_INCOMPATIBLE, "Reboot function not found in BOOT ROM");
}
struct picoboot_memory_access : public memory_access {
explicit picoboot_memory_access(picoboot::connection &connection) : connection(connection) {}
bool is_device() override {
return true;
}
uint32_t get_binary_start() override {
return FLASH_START;
}
void read(uint32_t address, uint8_t *buffer, uint size, __unused bool zero_fill) override {
if (flash == get_memory_type(address)) {
connection.exit_xip();
}
if (rom == get_memory_type(address) && (address+size) >= 0x2000) {
// read by memcpy instead
uint program_base = SRAM_START + 0x4000;
// program is "return memcpy(SRAM_BASE, 0, 0x4000);"
std::vector<uint32_t> program = {
0x07482101, // movs r1, #1; lsls r0, r1, #29
0x2100038a, // lsls r2, r1, #14; movs r1, #0
0x47184b00, // ldr r3, [pc, #0]; bx r3
bootrom_func_lookup(*this, rom_table_code('M','C'))
};
write_vector(program_base, program);
connection.exec(program_base);
// 4k is copied into the start of RAM
connection.read(SRAM_START + address, (uint8_t *) buffer, size);
} else if (is_transfer_aligned(address) && is_transfer_aligned(address + size)) {
connection.read(address, (uint8_t *) buffer, size);
} else {
if (flash == get_memory_type(address)) {
uint32_t aligned_start = address & ~(PAGE_SIZE - 1);
uint32_t aligned_end = (address + size + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1);
vector<uint8_t> tmp_buffer(aligned_end - aligned_start);
connection.read(aligned_start, tmp_buffer.data(), aligned_end - aligned_start);
std::copy(tmp_buffer.cbegin() + (address - aligned_start), tmp_buffer.cbegin() + (address + size - aligned_start), buffer);
} else {
std::stringstream sstream;
sstream << "Address range " << hex_string(address) << " + " << hex_string(size);
throw std::invalid_argument(sstream.str());
}
}
}
// note this does not automatically erase flash
void write(uint32_t address, uint8_t *buffer, uint size) {
if (flash == get_memory_type(address)) {
connection.exit_xip();
}
if (is_transfer_aligned(address) && is_transfer_aligned(address + size)) {
connection.write(address, (uint8_t *) buffer, size);
} else {
// for write, we must be correctly sized/aligned in 256 byte chunks
std::stringstream sstream;
sstream << "Address range " << hex_string(address) << " + " << hex_string(size);
throw std::invalid_argument(sstream.str());
}
}
template <typename T> void write_vector(uint32_t addr, vector<T> v) {
assert(!v.empty());
write(addr, (uint8_t *)v.data(), v.size() * sizeof(typename raw_type_mapping<T>::access_type));
}
private:
picoboot::connection& connection;
};
struct file_memory_access : public memory_access {
file_memory_access(FILE *file, range_map<size_t>& rmap, uint32_t binary_start) : file(file), rmap(rmap), binary_start(binary_start) {
}
uint32_t get_binary_start() override {
return binary_start;
}
void read(uint32_t address, uint8_t *buffer, uint32_t size, bool zero_fill) override {
while (size) {
uint this_size;
try {
auto result = rmap.get(address);
this_size = std::min(size, result.first.max_offset - result.first.offset);
assert(this_size);
fseek(file, result.second + result.first.offset, SEEK_SET);
fread(buffer, this_size, 1, file);
} catch (not_mapped_exception &e) {
if (zero_fill) {
// address is not in a range, so fill up to next range with zeros
this_size = rmap.next(address) - address;
this_size = std::min(this_size, size);
memset(buffer, 0, this_size);
} else {
throw e;
}
}
buffer += this_size;
address += this_size;
size -= this_size;
}
}
const range_map<size_t> &get_rmap() {
return rmap;
}
~file_memory_access() {
fclose(file);
}
private:
FILE *file;
range_map<size_t> rmap;
uint32_t binary_start;
};
struct remapped_memory_access : public memory_access {
remapped_memory_access(memory_access &wrap, range_map<uint32_t> rmap) : wrap(wrap), rmap(rmap) {}
void read(uint32_t address, uint8_t *buffer, uint size, bool zero_fill) override {
while (size) {
auto result = get_remapped(address);
uint this_size = std::min(size, result.first.max_offset - result.first.offset);
assert( this_size);
wrap.read(result.second + result.first.offset, buffer, this_size, zero_fill);
buffer += this_size;
address += this_size;
size -= this_size;
}
}
bool is_device() override {
return wrap.is_device();
}
uint32_t get_binary_start() override {
return wrap.get_binary_start(); // this is an absolute address
}
pair<range_map<uint32_t>::mapping, uint32_t> get_remapped(uint32_t address) {
try {
return rmap.get(address);
} catch (not_mapped_exception&) {
return std::make_pair(range_map<uint32_t>::mapping(0, rmap.next(address) - address), address);
}
}
private:
memory_access& wrap;
range_map<uint32_t> rmap;
};
static void read_and_check_elf32_header(FILE *in, elf32_header& eh_out) {
if (1 != fread(&eh_out, sizeof(eh_out), 1, in)) {
fail(ERROR_FORMAT, "'" + settings.filename +"' is not an ELF file");
}
if (eh_out.common.magic != ELF_MAGIC) {
fail(ERROR_FORMAT, "'" + settings.filename +"' is not an ELF file");
}
if (eh_out.common.version != 1 || eh_out.common.version2 != 1) {
fail(ERROR_FORMAT, "'" + settings.filename +"' has an unsupported ELF version");
}
if (eh_out.common.arch_class != 1 || eh_out.common.endianness != 1) {
fail(ERROR_INCOMPATIBLE, "'" + settings.filename +"' is not a 32 bit little-endian ELF");
}
if (eh_out.eh_size != sizeof(struct elf32_header)) {
fail(ERROR_FORMAT, "'" + settings.filename + "' is not valid");
}
if (eh_out.common.machine != EM_ARM) {
fail(ERROR_FORMAT, "'" + settings.filename +"' is not an ARM executable");
}
if (eh_out.common.abi != 0) {
fail(ERROR_INCOMPATIBLE, "'" + settings.filename +"' has the wrong architecture");
}
if (eh_out.flags & EF_ARM_ABI_FLOAT_HARD) {
fail(ERROR_INCOMPATIBLE, "'" + settings.filename +"' has the wrong architecture (hard float)");
}
}
static void __noreturn fail_read_error() {
fail(ERROR_READ_FAILED, "Failed to read input file");
}
static void __noreturn fail_write_error() {
fail(ERROR_WRITE_FAILED, "Failed to write output file");
}
struct binary_info_header {
vector<uint32_t> bi_addr;
range_map<uint32_t> reverse_copy_mapping;
};
bool find_binary_info(memory_access& access, binary_info_header &hdr) {
uint32_t base = access.get_binary_start();
if (!base) {
fail(ERROR_FORMAT, "UF2 file does not contain a valid RP2 executable image");
}
if (base == FLASH_START) base += 0x100;
vector<uint32_t> buffer = access.read_vector<uint32_t>(base, 64);
for(uint i=0;i<64;i++) {
if (buffer[i] == BINARY_INFO_MARKER_START) {
if (i + 4 < 64 && buffer[i+4] == BINARY_INFO_MARKER_END) {
uint32_t from = buffer[i+1];
uint32_t to = buffer[i+2];
enum memory_type from_type = get_memory_type(from);
enum memory_type to_type = get_memory_type(to);
if (to > from &&
from_type == to_type &&
is_size_aligned(from, 4) &&
is_size_aligned(to, 4)) {
access.read_into_vector(from, (to - from) / 4, hdr.bi_addr);
uint32_t cpy_table = buffer[i+3];
vector<uint32_t> mapping;
do {
mapping = access.read_vector<uint32_t>(cpy_table, 3);
if (!mapping[0]) break;
// from, to_start, to_end
hdr.reverse_copy_mapping.insert(range(mapping[1], mapping[2]), mapping[0]);