main.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. /*
  2. * Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
  3. *
  4. * SPDX-License-Identifier: BSD-3-Clause
  5. */
  6. #include <cstdio>
  7. #include <map>
  8. #include <set>
  9. #include <vector>
  10. #include <cstring>
  11. #include <cstdarg>
  12. #include <algorithm>
  13. #include "boot/uf2.h"
  14. #include "elf.h"
  15. typedef unsigned int uint;
  16. #define ERROR_ARGS -1
  17. #define ERROR_FORMAT -2
  18. #define ERROR_INCOMPATIBLE -3
  19. #define ERROR_READ_FAILED -4
  20. #define ERROR_WRITE_FAILED -5
  21. #define FLASH_SECTOR_ERASE_SIZE 4096u
  22. static char error_msg[512];
  23. static bool verbose;
  24. static int fail(int code, const char *format, ...) {
  25. va_list args;
  26. va_start(args, format);
  27. vsnprintf(error_msg, sizeof(error_msg), format, args);
  28. va_end(args);
  29. return code;
  30. }
  31. static int fail_read_error() {
  32. return fail(ERROR_READ_FAILED, "Failed to read input file");
  33. }
  34. static int fail_write_error() {
  35. return fail(ERROR_WRITE_FAILED, "Failed to write output file");
  36. }
  37. // we require 256 (as this is the page size supported by the device)
  38. #define LOG2_PAGE_SIZE 8u
  39. #define PAGE_SIZE (1u << LOG2_PAGE_SIZE)
  40. struct address_range {
  41. enum type {
  42. CONTENTS, // may have contents
  43. NO_CONTENTS, // must be uninitialized
  44. IGNORE // will be ignored
  45. };
  46. address_range(uint32_t from, uint32_t to, type type) : from(from), to(to), type(type) {}
  47. address_range() : address_range(0, 0, IGNORE) {}
  48. type type;
  49. uint32_t to;
  50. uint32_t from;
  51. };
  52. typedef std::vector<address_range> address_ranges;
  53. #define MAIN_RAM_START 0x20000000u // same as SRAM_BASE in addressmap.h
  54. #define MAIN_RAM_END 0x20042000u // same as SRAM_END in addressmap.h
  55. #define FLASH_START 0x10000000u // same as XIP_MAIN_BASE in addressmap.h
  56. #define FLASH_END 0x15000000u
  57. #define XIP_SRAM_START 0x15000000u // same as XIP_SRAM_BASE in addressmap.h
  58. #define XIP_SRAM_END 0x15004000u // same as XIP_SRAM_END in addressmap.h
  59. #define MAIN_RAM_BANKED_START 0x21000000u // same as SRAM0_BASE in addressmap.h
  60. #define MAIN_RAM_BANKED_END 0x21040000u
  61. #define ROM_START 0x00000000u // same as ROM_BASE in addressmap.h
  62. #define ROM_END 0x00004000u
  63. const address_ranges rp2040_address_ranges_flash {
  64. address_range(FLASH_START, FLASH_END, address_range::type::CONTENTS),
  65. address_range(MAIN_RAM_START, MAIN_RAM_END, address_range::type::NO_CONTENTS),
  66. address_range(MAIN_RAM_BANKED_START, MAIN_RAM_BANKED_END, address_range::type::NO_CONTENTS)
  67. };
  68. const address_ranges rp2040_address_ranges_ram {
  69. address_range(MAIN_RAM_START, MAIN_RAM_END, address_range::type::CONTENTS),
  70. address_range(XIP_SRAM_START, XIP_SRAM_END, address_range::type::CONTENTS),
  71. address_range(ROM_START, ROM_END, address_range::type::IGNORE) // for now we ignore the bootrom if present
  72. };
  73. struct page_fragment {
  74. page_fragment(uint32_t file_offset, uint32_t page_offset, uint32_t bytes) : file_offset(file_offset), page_offset(page_offset), bytes(bytes) {}
  75. uint32_t file_offset;
  76. uint32_t page_offset;
  77. uint32_t bytes;
  78. };
  79. static int usage() {
  80. fprintf(stderr, "Usage: elf2uf2 (-v) <input ELF file> <output UF2 file>\n");
  81. return ERROR_ARGS;
  82. }
  83. static int read_and_check_elf32_header(FILE *in, elf32_header& eh_out) {
  84. if (1 != fread(&eh_out, sizeof(eh_out), 1, in)) {
  85. return fail(ERROR_READ_FAILED, "Unable to read ELF header");
  86. }
  87. if (eh_out.common.magic != ELF_MAGIC) {
  88. return fail(ERROR_FORMAT, "Not an ELF file");
  89. }
  90. if (eh_out.common.version != 1 || eh_out.common.version2 != 1) {
  91. return fail(ERROR_FORMAT, "Unrecognized ELF version");
  92. }
  93. if (eh_out.common.arch_class != 1 || eh_out.common.endianness != 1) {
  94. return fail(ERROR_INCOMPATIBLE, "Require 32 bit little-endian ELF");
  95. }
  96. if (eh_out.eh_size != sizeof(struct elf32_header)) {
  97. return fail(ERROR_FORMAT, "Invalid ELF32 format");
  98. }
  99. if (eh_out.common.machine != EM_ARM) {
  100. return fail(ERROR_FORMAT, "Not an ARM executable");
  101. }
  102. if (eh_out.common.abi != 0) {
  103. return fail(ERROR_INCOMPATIBLE, "Unrecognized ABI");
  104. }
  105. if (eh_out.flags & EF_ARM_ABI_FLOAT_HARD) {
  106. return fail(ERROR_INCOMPATIBLE, "HARD-FLOAT not supported");
  107. }
  108. return 0;
  109. }
  110. int check_address_range(const address_ranges& valid_ranges, uint32_t addr, uint32_t vaddr, uint32_t size, bool uninitialized, address_range &ar) {
  111. for(const auto& range : valid_ranges) {
  112. if (range.from <= addr && range.to >= addr + size) {
  113. if (range.type == address_range::type::NO_CONTENTS && !uninitialized) {
  114. return fail(ERROR_INCOMPATIBLE, "ELF contains memory contents for uninitialized memory at %p", addr);
  115. }
  116. ar = range;
  117. if (verbose) {
  118. printf("%s segment %08x->%08x (%08x->%08x)\n", uninitialized ? "Uninitialized" : "Mapped", addr,
  119. addr + size, vaddr, vaddr+size);
  120. }
  121. return 0;
  122. }
  123. }
  124. return fail(ERROR_INCOMPATIBLE, "Memory segment %08x->%08x is outside of valid address range for device", addr, addr+size);
  125. }
  126. int read_elf32_ph_entries(FILE *in, const elf32_header &eh, std::vector<elf32_ph_entry>& entries) {
  127. if (eh.ph_entry_size != sizeof(elf32_ph_entry)) {
  128. return fail(ERROR_FORMAT, "Invalid ELF32 program header");
  129. }
  130. if (eh.ph_num) {
  131. entries.resize(eh.ph_num);
  132. if (fseek(in, eh.ph_offset, SEEK_SET)) {
  133. return fail_read_error();
  134. }
  135. if (eh.ph_num != fread(&entries[0], sizeof(struct elf32_ph_entry), eh.ph_num, in)) {
  136. return fail_read_error();
  137. }
  138. }
  139. return 0;
  140. }
  141. int check_elf32_ph_entries(const std::vector<elf32_ph_entry>& entries, const address_ranges& valid_ranges, std::map<uint32_t, std::vector<page_fragment>>& pages) {
  142. for(const auto & entry : entries) {
  143. if (entry.type == PT_LOAD && entry.memsz) {
  144. address_range ar;
  145. int rc;
  146. uint mapped_size = std::min(entry.filez, entry.memsz);
  147. if (mapped_size) {
  148. rc = check_address_range(valid_ranges, entry.paddr, entry.vaddr, mapped_size, false, ar);
  149. if (rc) return rc;
  150. // we don't download uninitialized, generally it is BSS and should be zero-ed by crt0.S, or it may be COPY areas which are undefined
  151. if (ar.type != address_range::type::CONTENTS) {
  152. if (verbose) printf(" ignored\n");
  153. continue;
  154. }
  155. uint addr = entry.paddr;
  156. uint remaining = mapped_size;
  157. uint file_offset = entry.offset;
  158. while (remaining) {
  159. uint off = addr & (PAGE_SIZE - 1);
  160. uint len = std::min(remaining, PAGE_SIZE - off);
  161. auto &fragments = pages[addr - off]; // list of fragments
  162. // note if filesz is zero, we want zero init which is handled because the
  163. // statement above creates an empty page fragment list
  164. // check overlap with any existing fragments
  165. for (const auto &fragment : fragments) {
  166. if ((off < fragment.page_offset + fragment.bytes) !=
  167. ((off + len) <= fragment.page_offset)) {
  168. fail(ERROR_FORMAT, "In memory segments overlap");
  169. }
  170. }
  171. fragments.push_back(
  172. page_fragment{file_offset,off,len});
  173. addr += len;
  174. file_offset += len;
  175. remaining -= len;
  176. }
  177. }
  178. if (entry.memsz > entry.filez) {
  179. // we have some uninitialized data too
  180. rc = check_address_range(valid_ranges, entry.paddr + entry.filez, entry.vaddr + entry.filez, entry.memsz - entry.filez, true,
  181. ar);
  182. if (rc) return rc;
  183. }
  184. }
  185. }
  186. return 0;
  187. }
  188. int realize_page(FILE *in, const std::vector<page_fragment> &fragments, uint8_t *buf, uint buf_len) {
  189. assert(buf_len >= PAGE_SIZE);
  190. for(auto& frag : fragments) {
  191. assert(frag.page_offset >= 0 && frag.page_offset < PAGE_SIZE && frag.page_offset + frag.bytes <= PAGE_SIZE);
  192. if (fseek(in, frag.file_offset, SEEK_SET)) {
  193. return fail_read_error();
  194. }
  195. if (1 != fread(buf + frag.page_offset, frag.bytes, 1, in)) {
  196. return fail_read_error();
  197. }
  198. }
  199. return 0;
  200. }
  201. static bool is_address_valid(const address_ranges& valid_ranges, uint32_t addr) {
  202. for(const auto& range : valid_ranges) {
  203. if (range.from <= addr && range.to > addr) {
  204. return true;
  205. }
  206. }
  207. return false;
  208. }
  209. static bool is_address_initialized(const address_ranges& valid_ranges, uint32_t addr) {
  210. for(const auto& range : valid_ranges) {
  211. if (range.from <= addr && range.to > addr) {
  212. return address_range::type::CONTENTS == range.type;
  213. }
  214. }
  215. return false;
  216. }
  217. static bool is_address_mapped(const std::map<uint32_t, std::vector<page_fragment>>& pages, uint32_t addr) {
  218. uint32_t page = addr & ~(PAGE_SIZE - 1);
  219. if (!pages.count(page)) return false;
  220. // todo check actual address within page
  221. return true;
  222. }
  223. static int determine_binary_type(const elf32_header &eh, const std::vector<elf32_ph_entry>& entries, bool *ram_style) {
  224. for(const auto &entry : entries) {
  225. if (entry.type == PT_LOAD && entry.memsz) {
  226. uint mapped_size = std::min(entry.filez, entry.memsz);
  227. if (mapped_size) {
  228. // we back convert the entrypoint from a VADDR to a PADDR to see if it originates in flash, and if
  229. // so call THAT a flash binary.
  230. if (eh.entry >= entry.vaddr && eh.entry < entry.vaddr + mapped_size) {
  231. uint32_t effective_entry = eh.entry + entry.paddr - entry.vaddr;
  232. if (is_address_initialized(rp2040_address_ranges_ram, effective_entry)) {
  233. *ram_style = true;
  234. return 0;
  235. } else if (is_address_initialized(rp2040_address_ranges_flash, effective_entry)) {
  236. *ram_style = false;
  237. return 0;
  238. }
  239. }
  240. }
  241. }
  242. }
  243. return fail(ERROR_INCOMPATIBLE, "entry point is not in mapped part of file");
  244. }
  245. int elf2uf2(FILE *in, FILE *out) {
  246. elf32_header eh;
  247. std::map<uint32_t, std::vector<page_fragment>> pages;
  248. int rc = read_and_check_elf32_header(in, eh);
  249. bool ram_style = false;
  250. address_ranges valid_ranges = {};
  251. if (!rc) {
  252. std::vector<elf32_ph_entry> entries;
  253. rc = read_elf32_ph_entries(in, eh, entries);
  254. if (!rc) {
  255. rc = determine_binary_type(eh, entries, &ram_style);
  256. }
  257. if (!rc) {
  258. if (verbose) {
  259. if (ram_style) {
  260. printf("Detected RAM binary\n");
  261. } else {
  262. printf("Detected FLASH binary\n");
  263. }
  264. }
  265. valid_ranges = ram_style ? rp2040_address_ranges_ram : rp2040_address_ranges_flash;
  266. rc = check_elf32_ph_entries(entries, valid_ranges, pages);
  267. }
  268. }
  269. if (rc) return rc;
  270. if (pages.empty()) {
  271. return fail(ERROR_INCOMPATIBLE, "The input file has no memory pages");
  272. }
  273. uint page_num = 0;
  274. if (ram_style) {
  275. uint32_t expected_ep_main_ram = UINT32_MAX;
  276. uint32_t expected_ep_xip_sram = UINT32_MAX;
  277. for(auto& page_entry : pages) {
  278. if ( ((page_entry.first >= MAIN_RAM_START) && (page_entry.first < MAIN_RAM_END)) && (page_entry.first < expected_ep_main_ram) ) {
  279. expected_ep_main_ram = page_entry.first | 0x1;
  280. } else if ( ((page_entry.first >= XIP_SRAM_START) && (page_entry.first < XIP_SRAM_END)) && (page_entry.first < expected_ep_xip_sram) ) {
  281. expected_ep_xip_sram = page_entry.first | 0x1;
  282. }
  283. }
  284. uint32_t expected_ep = (UINT32_MAX != expected_ep_main_ram) ? expected_ep_main_ram : expected_ep_xip_sram;
  285. if (eh.entry == expected_ep_xip_sram) {
  286. return fail(ERROR_INCOMPATIBLE, "B0/B1 Boot ROM does not support direct entry into XIP_SRAM\n");
  287. } else if (eh.entry != expected_ep) {
  288. return fail(ERROR_INCOMPATIBLE, "A RAM binary should have an entry point at the beginning: %08x (not %08x)\n", expected_ep, eh.entry);
  289. }
  290. pico_static_assert(0 == (MAIN_RAM_START & (PAGE_SIZE - 1)), "");
  291. // currently don't require this as entry point is now at the start, we don't know where reset vector is
  292. #if 0
  293. uint8_t buf[PAGE_SIZE];
  294. rc = realize_page(in, pages[MAIN_RAM_START], buf, sizeof(buf));
  295. if (rc) return rc;
  296. uint32_t sp = ((uint32_t *)buf)[0];
  297. uint32_t ip = ((uint32_t *)buf)[1];
  298. if (!is_address_mapped(pages, ip)) {
  299. return fail(ERROR_INCOMPATIBLE, "Vector table at %08x is invalid: reset vector %08x is not in mapped memory",
  300. MAIN_RAM_START, ip);
  301. }
  302. if (!is_address_valid(valid_ranges, sp - 4)) {
  303. return fail(ERROR_INCOMPATIBLE, "Vector table at %08x is invalid: stack pointer %08x is not in RAM",
  304. MAIN_RAM_START, sp);
  305. }
  306. #endif
  307. } else {
  308. // Fill in empty dummy uf2 pages to align the binary to flash sectors (except for the last sector which we don't
  309. // need to pad, and choose not to to avoid making all SDK UF2s bigger)
  310. // That workaround is required because the bootrom uses the block number for erase sector calculations:
  311. // https://github.com/raspberrypi/pico-bootrom/blob/c09c7f08550e8a36fc38dc74f8873b9576de99eb/bootrom/virtual_disk.c#L205
  312. std::set<uint32_t> touched_sectors;
  313. for (auto& page_entry : pages) {
  314. uint32_t sector = page_entry.first / FLASH_SECTOR_ERASE_SIZE;
  315. touched_sectors.insert(sector);
  316. }
  317. uint32_t last_page = pages.rbegin()->first;
  318. for (uint32_t sector : touched_sectors) {
  319. for (uint32_t page = sector * FLASH_SECTOR_ERASE_SIZE; page < (sector + 1) * FLASH_SECTOR_ERASE_SIZE; page += PAGE_SIZE) {
  320. if (page < last_page) {
  321. // Create a dummy page, if it does not exist yet. note that all present pages are first
  322. // zeroed before they are filled with any contents, so a dummy page will be all zeros.
  323. auto &dummy = pages[page];
  324. }
  325. }
  326. }
  327. }
  328. uf2_block block;
  329. block.magic_start0 = UF2_MAGIC_START0;
  330. block.magic_start1 = UF2_MAGIC_START1;
  331. block.flags = UF2_FLAG_FAMILY_ID_PRESENT;
  332. block.payload_size = PAGE_SIZE;
  333. block.num_blocks = (uint32_t)pages.size();
  334. block.file_size = RP2040_FAMILY_ID;
  335. block.magic_end = UF2_MAGIC_END;
  336. for(auto& page_entry : pages) {
  337. block.target_addr = page_entry.first;
  338. block.block_no = page_num++;
  339. if (verbose) {
  340. printf("Page %d / %d %08x%s\n", block.block_no, block.num_blocks, block.target_addr,
  341. page_entry.second.empty() ? " (padding)": "");
  342. }
  343. memset(block.data, 0, sizeof(block.data));
  344. rc = realize_page(in, page_entry.second, block.data, sizeof(block.data));
  345. if (rc) return rc;
  346. if (1 != fwrite(&block, sizeof(uf2_block), 1, out)) {
  347. return fail_write_error();
  348. }
  349. }
  350. return 0;
  351. }
  352. int main(int argc, char **argv) {
  353. int arg = 1;
  354. if (arg < argc && !strcmp(argv[arg], "-v")) {
  355. verbose = true;
  356. arg++;
  357. }
  358. if (argc < arg + 2) {
  359. return usage();
  360. }
  361. const char *in_filename = argv[arg++];
  362. FILE *in = fopen(in_filename, "rb");
  363. if (!in) {
  364. fprintf(stderr, "Can't open input file '%s'\n", in_filename);
  365. return ERROR_ARGS;
  366. }
  367. const char *out_filename = argv[arg++];
  368. FILE *out = fopen(out_filename, "wb");
  369. if (!out) {
  370. fprintf(stderr, "Can't open output file '%s'\n", out_filename);
  371. return ERROR_ARGS;
  372. }
  373. int rc = elf2uf2(in, out);
  374. fclose(in);
  375. fclose(out);
  376. if (rc) {
  377. remove(out_filename);
  378. if (error_msg[0]) {
  379. fprintf(stderr, "ERROR: %s\n", error_msg);
  380. }
  381. }
  382. return rc;
  383. }