main.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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 <vector>
  9. #include <cstring>
  10. #include <cstdarg>
  11. #include <algorithm>
  12. #include "boot/uf2.h"
  13. #include "elf.h"
  14. typedef unsigned int uint;
  15. #define ERROR_ARGS -1
  16. #define ERROR_FORMAT -2
  17. #define ERROR_INCOMPATIBLE -3
  18. #define ERROR_READ_FAILED -4
  19. #define ERROR_WRITE_FAILED -5
  20. static char error_msg[512];
  21. static bool verbose;
  22. static int fail(int code, const char *format, ...) {
  23. va_list args;
  24. va_start(args, format);
  25. vsnprintf(error_msg, sizeof(error_msg), format, args);
  26. va_end(args);
  27. return code;
  28. }
  29. static int fail_read_error() {
  30. return fail(ERROR_READ_FAILED, "Failed to read input file");
  31. }
  32. static int fail_write_error() {
  33. return fail(ERROR_WRITE_FAILED, "Failed to write output file");
  34. }
  35. // we require 256 (as this is the page size supported by the device)
  36. #define LOG2_PAGE_SIZE 8u
  37. #define PAGE_SIZE (1u << LOG2_PAGE_SIZE)
  38. struct address_range {
  39. enum type {
  40. CONTENTS, // may have contents
  41. NO_CONTENTS, // must be uninitialized
  42. IGNORE // will be ignored
  43. };
  44. address_range(uint32_t from, uint32_t to, type type) : from(from), to(to), type(type) {}
  45. address_range() : address_range(0, 0, IGNORE) {}
  46. type type;
  47. uint32_t to;
  48. uint32_t from;
  49. };
  50. typedef std::vector<address_range> address_ranges;
  51. #define MAIN_RAM_START 0x20000000u
  52. #define MAIN_RAM_END 0x20042000u
  53. #define FLASH_START 0x10000000u
  54. #define FLASH_END 0x15000000u
  55. const address_ranges rp2040_address_ranges_flash {
  56. address_range(FLASH_START, FLASH_END, address_range::type::CONTENTS),
  57. address_range(MAIN_RAM_START, MAIN_RAM_END, address_range::type::NO_CONTENTS)
  58. };
  59. const address_ranges rp2040_address_ranges_ram {
  60. address_range(MAIN_RAM_START, MAIN_RAM_END, address_range::type::CONTENTS),
  61. address_range(0x00000000u, 0x00002000u, address_range::type::IGNORE) // for now we ignore the bootrom if present
  62. };
  63. struct page_fragment {
  64. page_fragment(uint32_t file_offset, uint32_t page_offset, uint32_t bytes) : file_offset(file_offset), page_offset(page_offset), bytes(bytes) {}
  65. uint32_t file_offset;
  66. uint32_t page_offset;
  67. uint32_t bytes;
  68. };
  69. static int usage() {
  70. fprintf(stderr, "Usage: elf2uf2 (-v) <input ELF file> <output UF2 file>\n");
  71. return ERROR_ARGS;
  72. }
  73. static int read_and_check_elf32_header(FILE *in, elf32_header& eh_out) {
  74. if (1 != fread(&eh_out, sizeof(eh_out), 1, in)) {
  75. return fail(ERROR_READ_FAILED, "Unable to read ELF header");
  76. }
  77. if (eh_out.common.magic != ELF_MAGIC) {
  78. return fail(ERROR_FORMAT, "Not an ELF file");
  79. }
  80. if (eh_out.common.version != 1 || eh_out.common.version2 != 1) {
  81. return fail(ERROR_FORMAT, "Unrecognized ELF version");
  82. }
  83. if (eh_out.common.arch_class != 1 || eh_out.common.endianness != 1) {
  84. return fail(ERROR_INCOMPATIBLE, "Require 32 bit little-endian ELF");
  85. }
  86. if (eh_out.eh_size != sizeof(struct elf32_header)) {
  87. return fail(ERROR_FORMAT, "Invalid ELF32 format");
  88. }
  89. if (eh_out.common.machine != EM_ARM) {
  90. return fail(ERROR_FORMAT, "Not an ARM executable");
  91. }
  92. if (eh_out.common.abi != 0) {
  93. return fail(ERROR_INCOMPATIBLE, "Unrecognized ABI");
  94. }
  95. if (eh_out.flags & EF_ARM_ABI_FLOAT_HARD) {
  96. return fail(ERROR_INCOMPATIBLE, "HARD-FLOAT not supported");
  97. }
  98. return 0;
  99. }
  100. int check_address_range(const address_ranges& valid_ranges, uint32_t addr, uint32_t vaddr, uint32_t size, bool uninitialized, address_range &ar) {
  101. for(const auto& range : valid_ranges) {
  102. if (range.from <= addr && range.to >= addr + size) {
  103. if (range.type == address_range::type::NO_CONTENTS && !uninitialized) {
  104. return fail(ERROR_INCOMPATIBLE, "ELF contains memory contents for uninitialized memory");
  105. }
  106. ar = range;
  107. if (verbose) {
  108. printf("%s segment %08x->%08x (%08x->%08x)\n", uninitialized ? "Uninitialized" : "Mapped", addr,
  109. addr + size, vaddr, vaddr+size);
  110. }
  111. return 0;
  112. }
  113. }
  114. return fail(ERROR_INCOMPATIBLE, "Memory segment %08x->%08x is outside of valid address range for device", addr, addr+size);
  115. }
  116. int read_and_check_elf32_ph_entries(FILE *in, const elf32_header &eh, const address_ranges& valid_ranges, std::map<uint32_t, std::vector<page_fragment>>& pages) {
  117. if (eh.ph_entry_size != sizeof(elf32_ph_entry)) {
  118. return fail(ERROR_FORMAT, "Invalid ELF32 program header");
  119. }
  120. if (eh.ph_num) {
  121. std::vector<elf32_ph_entry> entries(eh.ph_num);
  122. if (eh.ph_num != fread(&entries[0], sizeof(struct elf32_ph_entry), eh.ph_num, in)) {
  123. return fail_read_error();
  124. }
  125. for(uint i=0;i<eh.ph_num;i++) {
  126. elf32_ph_entry& entry = entries[i];
  127. if (entry.type == PT_LOAD && entry.memsz) {
  128. address_range ar;
  129. int rc;
  130. uint mapped_size = std::min(entry.filez, entry.memsz);
  131. if (mapped_size) {
  132. rc = check_address_range(valid_ranges, entry.paddr, entry.vaddr, mapped_size, false, ar);
  133. if (rc) return rc;
  134. // 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
  135. if (ar.type != address_range::type::CONTENTS) {
  136. if (verbose) printf(" ignored\n");
  137. continue;
  138. }
  139. uint addr = entry.paddr;
  140. uint remaining = mapped_size;
  141. uint file_offset = entry.offset;
  142. while (remaining) {
  143. uint off = addr & (PAGE_SIZE - 1);
  144. uint len = std::min(remaining, PAGE_SIZE - off);
  145. auto &fragments = pages[addr - off]; // list of fragments
  146. // note if filesz is zero, we want zero init which is handled because the
  147. // statement above creates an empty page fragment list
  148. // check overlap with any existing fragments
  149. for (const auto &fragment : fragments) {
  150. if ((off < fragment.page_offset + fragment.bytes) !=
  151. ((off + len) <= fragment.page_offset)) {
  152. fail(ERROR_FORMAT, "In memory segments overlap");
  153. }
  154. }
  155. fragments.push_back(
  156. page_fragment{file_offset,off,len});
  157. addr += len;
  158. file_offset += len;
  159. remaining -= len;
  160. }
  161. }
  162. if (entry.memsz > entry.filez) {
  163. // we have some uninitialized data too
  164. rc = check_address_range(valid_ranges, entry.paddr + entry.filez, entry.vaddr + entry.filez, entry.memsz - entry.filez, true,
  165. ar);
  166. if (rc) return rc;
  167. }
  168. }
  169. }
  170. }
  171. return 0;
  172. }
  173. int realize_page(FILE *in, const std::vector<page_fragment> &fragments, uint8_t *buf, uint buf_len) {
  174. assert(buf_len >= PAGE_SIZE);
  175. for(auto& frag : fragments) {
  176. assert(frag.page_offset >= 0 && frag.page_offset < PAGE_SIZE && frag.page_offset + frag.bytes <= PAGE_SIZE);
  177. if (fseek(in, frag.file_offset, SEEK_SET)) {
  178. return fail_read_error();
  179. }
  180. if (1 != fread(buf + frag.page_offset, frag.bytes, 1, in)) {
  181. return fail_read_error();
  182. }
  183. }
  184. return 0;
  185. }
  186. static bool is_address_valid(const address_ranges& valid_ranges, uint32_t addr) {
  187. for(const auto& range : valid_ranges) {
  188. if (range.from <= addr && range.to > addr) {
  189. return true;
  190. }
  191. }
  192. return false;
  193. }
  194. static bool is_address_mapped(const std::map<uint32_t, std::vector<page_fragment>>& pages, uint32_t addr) {
  195. uint32_t page = addr & ~(PAGE_SIZE - 1);
  196. if (!pages.count(page)) return false;
  197. // todo check actual address within page
  198. return true;
  199. }
  200. int elf2uf2(FILE *in, FILE *out) {
  201. elf32_header eh;
  202. std::map<uint32_t, std::vector<page_fragment>> pages;
  203. int rc = read_and_check_elf32_header(in, eh);
  204. bool ram_style = false;
  205. address_ranges valid_ranges = {};
  206. if (!rc) {
  207. ram_style = 0x2 == eh.entry >> 28u;
  208. if (verbose) {
  209. if (ram_style) {
  210. printf("Detected RAM binary\n");
  211. } else {
  212. printf("Detected FLASH binary\n");
  213. }
  214. }
  215. valid_ranges = ram_style ? rp2040_address_ranges_ram : rp2040_address_ranges_flash;
  216. rc = read_and_check_elf32_ph_entries(in, eh, valid_ranges, pages);
  217. }
  218. if (rc) return rc;
  219. if (pages.empty()) {
  220. return fail(ERROR_INCOMPATIBLE, "The input file has no memory pages");
  221. }
  222. uint page_num = 0;
  223. if (ram_style) {
  224. uint32_t expected_ep = pages.begin()->first | 0x1;
  225. if (eh.entry != expected_ep) {
  226. return fail(ERROR_INCOMPATIBLE, "A RAM binary should have an entry point at the beginning: %08x (not %08x)\n", expected_ep, eh.entry);
  227. }
  228. static_assert(0 == (MAIN_RAM_START & (PAGE_SIZE - 1)), "");
  229. // currently don't require this as entry point is now at the start, we don't know where reset vector is
  230. #if 0
  231. uint8_t buf[PAGE_SIZE];
  232. rc = realize_page(in, pages[MAIN_RAM_START], buf, sizeof(buf));
  233. if (rc) return rc;
  234. uint32_t sp = ((uint32_t *)buf)[0];
  235. uint32_t ip = ((uint32_t *)buf)[1];
  236. if (!is_address_mapped(pages, ip)) {
  237. return fail(ERROR_INCOMPATIBLE, "Vector table at %08x is invalid: reset vector %08x is not in mapped memory",
  238. MAIN_RAM_START, ip);
  239. }
  240. if (!is_address_valid(valid_ranges, sp - 4)) {
  241. return fail(ERROR_INCOMPATIBLE, "Vector table at %08x is invalid: stack pointer %08x is not in RAM",
  242. MAIN_RAM_START, sp);
  243. }
  244. #endif
  245. }
  246. uf2_block block;
  247. block.magic_start0 = UF2_MAGIC_START0;
  248. block.magic_start1 = UF2_MAGIC_START1;
  249. block.flags = UF2_FLAG_FAMILY_ID_PRESENT;
  250. block.payload_size = PAGE_SIZE;
  251. block.num_blocks = (uint32_t)pages.size();
  252. block.file_size = RP2040_FAMILY_ID;
  253. block.magic_end = UF2_MAGIC_END;
  254. for(auto& page_entry : pages) {
  255. block.target_addr = page_entry.first;
  256. block.block_no = page_num++;
  257. if (verbose) {
  258. printf("Page %d / %d %08x\n", block.block_no, block.num_blocks, block.target_addr);
  259. }
  260. memset(block.data, 0, sizeof(block.data));
  261. rc = realize_page(in, page_entry.second, block.data, sizeof(block.data));
  262. if (rc) return rc;
  263. if (1 != fwrite(&block, sizeof(uf2_block), 1, out)) {
  264. return fail_write_error();
  265. }
  266. }
  267. return 0;
  268. }
  269. int main(int argc, char **argv) {
  270. int arg = 1;
  271. if (arg < argc && !strcmp(argv[arg], "-v")) {
  272. verbose = true;
  273. arg++;
  274. }
  275. if (argc < arg + 2) {
  276. return usage();
  277. }
  278. const char *in_filename = argv[arg++];
  279. FILE *in = fopen(in_filename, "rb");
  280. if (!in) {
  281. fprintf(stderr, "Can't open input file '%s'\n", in_filename);
  282. return ERROR_ARGS;
  283. }
  284. const char *out_filename = argv[arg++];
  285. FILE *out = fopen(out_filename, "wb");
  286. if (!out) {
  287. fprintf(stderr, "Can't open output file '%s'\n", out_filename);
  288. return ERROR_ARGS;
  289. }
  290. int rc = elf2uf2(in, out);
  291. fclose(in);
  292. fclose(out);
  293. if (rc) {
  294. remove(out_filename);
  295. if (error_msg[0]) {
  296. fprintf(stderr, "ERROR: %s\n", error_msg);
  297. }
  298. }
  299. return rc;
  300. }