loader.c 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913
  1. /*
  2. * QEMU Executable loader
  3. *
  4. * Copyright (c) 2006 Fabrice Bellard
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  19. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. *
  24. * Gunzip functionality in this file is derived from u-boot:
  25. *
  26. * (C) Copyright 2008 Semihalf
  27. *
  28. * (C) Copyright 2000-2005
  29. * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
  30. *
  31. * This program is free software; you can redistribute it and/or
  32. * modify it under the terms of the GNU General Public License as
  33. * published by the Free Software Foundation; either version 2 of
  34. * the License, or (at your option) any later version.
  35. *
  36. * This program is distributed in the hope that it will be useful,
  37. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  38. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  39. * GNU General Public License for more details.
  40. *
  41. * You should have received a copy of the GNU General Public License along
  42. * with this program; if not, see <http://www.gnu.org/licenses/>.
  43. */
  44. #include "qemu/osdep.h"
  45. #include "qemu/datadir.h"
  46. #include "qemu/error-report.h"
  47. #include "qapi/error.h"
  48. #include "qapi/qapi-commands-machine.h"
  49. #include "qapi/type-helpers.h"
  50. #include "trace.h"
  51. #include "hw/hw.h"
  52. #include "disas/disas.h"
  53. #include "migration/vmstate.h"
  54. #include "monitor/monitor.h"
  55. #include "system/reset.h"
  56. #include "system/system.h"
  57. #include "uboot_image.h"
  58. #include "hw/loader.h"
  59. #include "hw/nvram/fw_cfg.h"
  60. #include "exec/memory.h"
  61. #include "hw/boards.h"
  62. #include "qemu/cutils.h"
  63. #include "system/runstate.h"
  64. #include "tcg/debuginfo.h"
  65. #include <zlib.h>
  66. static int roms_loaded;
  67. /* return the size or -1 if error */
  68. int64_t get_image_size(const char *filename)
  69. {
  70. int fd;
  71. int64_t size;
  72. fd = open(filename, O_RDONLY | O_BINARY);
  73. if (fd < 0)
  74. return -1;
  75. size = lseek(fd, 0, SEEK_END);
  76. close(fd);
  77. return size;
  78. }
  79. /* return the size or -1 if error */
  80. ssize_t load_image_size(const char *filename, void *addr, size_t size)
  81. {
  82. int fd;
  83. ssize_t actsize, l = 0;
  84. fd = open(filename, O_RDONLY | O_BINARY);
  85. if (fd < 0) {
  86. return -1;
  87. }
  88. while ((actsize = read(fd, addr + l, size - l)) > 0) {
  89. l += actsize;
  90. }
  91. close(fd);
  92. return actsize < 0 ? -1 : l;
  93. }
  94. /* read()-like version */
  95. ssize_t read_targphys(const char *name,
  96. int fd, hwaddr dst_addr, size_t nbytes)
  97. {
  98. uint8_t *buf;
  99. ssize_t did;
  100. buf = g_malloc(nbytes);
  101. did = read(fd, buf, nbytes);
  102. if (did > 0)
  103. rom_add_blob_fixed("read", buf, did, dst_addr);
  104. g_free(buf);
  105. return did;
  106. }
  107. ssize_t load_image_targphys(const char *filename,
  108. hwaddr addr, uint64_t max_sz)
  109. {
  110. return load_image_targphys_as(filename, addr, max_sz, NULL);
  111. }
  112. /* return the size or -1 if error */
  113. ssize_t load_image_targphys_as(const char *filename,
  114. hwaddr addr, uint64_t max_sz, AddressSpace *as)
  115. {
  116. ssize_t size;
  117. size = get_image_size(filename);
  118. if (size < 0 || size > max_sz) {
  119. return -1;
  120. }
  121. if (size > 0) {
  122. if (rom_add_file_fixed_as(filename, addr, -1, as) < 0) {
  123. return -1;
  124. }
  125. }
  126. return size;
  127. }
  128. ssize_t load_image_mr(const char *filename, MemoryRegion *mr)
  129. {
  130. ssize_t size;
  131. if (!memory_access_is_direct(mr, false)) {
  132. /* Can only load an image into RAM or ROM */
  133. return -1;
  134. }
  135. size = get_image_size(filename);
  136. if (size < 0 || size > memory_region_size(mr)) {
  137. return -1;
  138. }
  139. if (size > 0) {
  140. if (rom_add_file_mr(filename, mr, -1) < 0) {
  141. return -1;
  142. }
  143. }
  144. return size;
  145. }
  146. void pstrcpy_targphys(const char *name, hwaddr dest, int buf_size,
  147. const char *source)
  148. {
  149. const char *nulp;
  150. char *ptr;
  151. if (buf_size <= 0) return;
  152. nulp = memchr(source, 0, buf_size);
  153. if (nulp) {
  154. rom_add_blob_fixed(name, source, (nulp - source) + 1, dest);
  155. } else {
  156. rom_add_blob_fixed(name, source, buf_size, dest);
  157. ptr = rom_ptr(dest + buf_size - 1, sizeof(*ptr));
  158. *ptr = 0;
  159. }
  160. }
  161. /* A.OUT loader */
  162. struct exec
  163. {
  164. uint32_t a_info; /* Use macros N_MAGIC, etc for access */
  165. uint32_t a_text; /* length of text, in bytes */
  166. uint32_t a_data; /* length of data, in bytes */
  167. uint32_t a_bss; /* length of uninitialized data area, in bytes */
  168. uint32_t a_syms; /* length of symbol table data in file, in bytes */
  169. uint32_t a_entry; /* start address */
  170. uint32_t a_trsize; /* length of relocation info for text, in bytes */
  171. uint32_t a_drsize; /* length of relocation info for data, in bytes */
  172. };
  173. static void bswap_ahdr(struct exec *e)
  174. {
  175. bswap32s(&e->a_info);
  176. bswap32s(&e->a_text);
  177. bswap32s(&e->a_data);
  178. bswap32s(&e->a_bss);
  179. bswap32s(&e->a_syms);
  180. bswap32s(&e->a_entry);
  181. bswap32s(&e->a_trsize);
  182. bswap32s(&e->a_drsize);
  183. }
  184. #define N_MAGIC(exec) ((exec).a_info & 0xffff)
  185. #define OMAGIC 0407
  186. #define NMAGIC 0410
  187. #define ZMAGIC 0413
  188. #define QMAGIC 0314
  189. #define _N_HDROFF(x) (1024 - sizeof (struct exec))
  190. #define N_TXTOFF(x) \
  191. (N_MAGIC(x) == ZMAGIC ? _N_HDROFF((x)) + sizeof (struct exec) : \
  192. (N_MAGIC(x) == QMAGIC ? 0 : sizeof (struct exec)))
  193. #define N_TXTADDR(x, target_page_size) (N_MAGIC(x) == QMAGIC ? target_page_size : 0)
  194. #define _N_SEGMENT_ROUND(x, target_page_size) (((x) + target_page_size - 1) & ~(target_page_size - 1))
  195. #define _N_TXTENDADDR(x, target_page_size) (N_TXTADDR(x, target_page_size)+(x).a_text)
  196. #define N_DATADDR(x, target_page_size) \
  197. (N_MAGIC(x)==OMAGIC? (_N_TXTENDADDR(x, target_page_size)) \
  198. : (_N_SEGMENT_ROUND (_N_TXTENDADDR(x, target_page_size), target_page_size)))
  199. ssize_t load_aout(const char *filename, hwaddr addr, int max_sz,
  200. int bswap_needed, hwaddr target_page_size)
  201. {
  202. int fd;
  203. ssize_t size, ret;
  204. struct exec e;
  205. uint32_t magic;
  206. fd = open(filename, O_RDONLY | O_BINARY);
  207. if (fd < 0)
  208. return -1;
  209. size = read(fd, &e, sizeof(e));
  210. if (size < 0)
  211. goto fail;
  212. if (bswap_needed) {
  213. bswap_ahdr(&e);
  214. }
  215. magic = N_MAGIC(e);
  216. switch (magic) {
  217. case ZMAGIC:
  218. case QMAGIC:
  219. case OMAGIC:
  220. if (e.a_text + e.a_data > max_sz)
  221. goto fail;
  222. lseek(fd, N_TXTOFF(e), SEEK_SET);
  223. size = read_targphys(filename, fd, addr, e.a_text + e.a_data);
  224. if (size < 0)
  225. goto fail;
  226. break;
  227. case NMAGIC:
  228. if (N_DATADDR(e, target_page_size) + e.a_data > max_sz)
  229. goto fail;
  230. lseek(fd, N_TXTOFF(e), SEEK_SET);
  231. size = read_targphys(filename, fd, addr, e.a_text);
  232. if (size < 0)
  233. goto fail;
  234. ret = read_targphys(filename, fd, addr + N_DATADDR(e, target_page_size),
  235. e.a_data);
  236. if (ret < 0)
  237. goto fail;
  238. size += ret;
  239. break;
  240. default:
  241. goto fail;
  242. }
  243. close(fd);
  244. return size;
  245. fail:
  246. close(fd);
  247. return -1;
  248. }
  249. /* ELF loader */
  250. static void *load_at(int fd, off_t offset, size_t size)
  251. {
  252. void *ptr;
  253. if (lseek(fd, offset, SEEK_SET) < 0)
  254. return NULL;
  255. ptr = g_malloc(size);
  256. if (read(fd, ptr, size) != size) {
  257. g_free(ptr);
  258. return NULL;
  259. }
  260. return ptr;
  261. }
  262. #ifdef ELF_CLASS
  263. #undef ELF_CLASS
  264. #endif
  265. #define ELF_CLASS ELFCLASS32
  266. #include "elf.h"
  267. #define SZ 32
  268. #define elf_word uint32_t
  269. #define elf_sword int32_t
  270. #define bswapSZs bswap32s
  271. #include "hw/elf_ops.h.inc"
  272. #undef elfhdr
  273. #undef elf_phdr
  274. #undef elf_shdr
  275. #undef elf_sym
  276. #undef elf_rela
  277. #undef elf_note
  278. #undef elf_word
  279. #undef elf_sword
  280. #undef bswapSZs
  281. #undef SZ
  282. #define elfhdr elf64_hdr
  283. #define elf_phdr elf64_phdr
  284. #define elf_note elf64_note
  285. #define elf_shdr elf64_shdr
  286. #define elf_sym elf64_sym
  287. #define elf_rela elf64_rela
  288. #define elf_word uint64_t
  289. #define elf_sword int64_t
  290. #define bswapSZs bswap64s
  291. #define SZ 64
  292. #include "hw/elf_ops.h.inc"
  293. const char *load_elf_strerror(ssize_t error)
  294. {
  295. switch (error) {
  296. case 0:
  297. return "No error";
  298. case ELF_LOAD_FAILED:
  299. return "Failed to load ELF";
  300. case ELF_LOAD_NOT_ELF:
  301. return "The image is not ELF";
  302. case ELF_LOAD_WRONG_ARCH:
  303. return "The image is from incompatible architecture";
  304. case ELF_LOAD_WRONG_ENDIAN:
  305. return "The image has incorrect endianness";
  306. case ELF_LOAD_TOO_BIG:
  307. return "The image segments are too big to load";
  308. default:
  309. return "Unknown error";
  310. }
  311. }
  312. void load_elf_hdr(const char *filename, void *hdr, bool *is64, Error **errp)
  313. {
  314. int fd;
  315. uint8_t e_ident_local[EI_NIDENT];
  316. uint8_t *e_ident;
  317. size_t hdr_size, off;
  318. bool is64l;
  319. if (!hdr) {
  320. hdr = e_ident_local;
  321. }
  322. e_ident = hdr;
  323. fd = open(filename, O_RDONLY | O_BINARY);
  324. if (fd < 0) {
  325. error_setg_errno(errp, errno, "Failed to open file: %s", filename);
  326. return;
  327. }
  328. if (read(fd, hdr, EI_NIDENT) != EI_NIDENT) {
  329. error_setg_errno(errp, errno, "Failed to read file: %s", filename);
  330. goto fail;
  331. }
  332. if (e_ident[0] != ELFMAG0 ||
  333. e_ident[1] != ELFMAG1 ||
  334. e_ident[2] != ELFMAG2 ||
  335. e_ident[3] != ELFMAG3) {
  336. error_setg(errp, "Bad ELF magic");
  337. goto fail;
  338. }
  339. is64l = e_ident[EI_CLASS] == ELFCLASS64;
  340. hdr_size = is64l ? sizeof(Elf64_Ehdr) : sizeof(Elf32_Ehdr);
  341. if (is64) {
  342. *is64 = is64l;
  343. }
  344. off = EI_NIDENT;
  345. while (hdr != e_ident_local && off < hdr_size) {
  346. size_t br = read(fd, hdr + off, hdr_size - off);
  347. switch (br) {
  348. case 0:
  349. error_setg(errp, "File too short: %s", filename);
  350. goto fail;
  351. case -1:
  352. error_setg_errno(errp, errno, "Failed to read file: %s",
  353. filename);
  354. goto fail;
  355. }
  356. off += br;
  357. }
  358. fail:
  359. close(fd);
  360. }
  361. /* return < 0 if error, otherwise the number of bytes loaded in memory */
  362. ssize_t load_elf(const char *filename,
  363. uint64_t (*elf_note_fn)(void *, void *, bool),
  364. uint64_t (*translate_fn)(void *, uint64_t),
  365. void *translate_opaque, uint64_t *pentry, uint64_t *lowaddr,
  366. uint64_t *highaddr, uint32_t *pflags, int big_endian,
  367. int elf_machine, int clear_lsb, int data_swab)
  368. {
  369. return load_elf_as(filename, elf_note_fn, translate_fn, translate_opaque,
  370. pentry, lowaddr, highaddr, pflags,
  371. big_endian ? ELFDATA2MSB : ELFDATA2LSB,
  372. elf_machine, clear_lsb, data_swab, NULL);
  373. }
  374. /* return < 0 if error, otherwise the number of bytes loaded in memory */
  375. ssize_t load_elf_as(const char *filename,
  376. uint64_t (*elf_note_fn)(void *, void *, bool),
  377. uint64_t (*translate_fn)(void *, uint64_t),
  378. void *translate_opaque, uint64_t *pentry, uint64_t *lowaddr,
  379. uint64_t *highaddr, uint32_t *pflags, int elf_data_order,
  380. int elf_machine, int clear_lsb, int data_swab,
  381. AddressSpace *as)
  382. {
  383. return load_elf_ram_sym(filename, elf_note_fn,
  384. translate_fn, translate_opaque,
  385. pentry, lowaddr, highaddr, pflags, elf_data_order,
  386. elf_machine, clear_lsb, data_swab, as,
  387. true, NULL);
  388. }
  389. /* return < 0 if error, otherwise the number of bytes loaded in memory */
  390. ssize_t load_elf_ram_sym(const char *filename,
  391. uint64_t (*elf_note_fn)(void *, void *, bool),
  392. uint64_t (*translate_fn)(void *, uint64_t),
  393. void *translate_opaque, uint64_t *pentry,
  394. uint64_t *lowaddr, uint64_t *highaddr,
  395. uint32_t *pflags, int elf_data_order, int elf_machine,
  396. int clear_lsb, int data_swab,
  397. AddressSpace *as, bool load_rom, symbol_fn_t sym_cb)
  398. {
  399. const int host_data_order = HOST_BIG_ENDIAN ? ELFDATA2MSB : ELFDATA2LSB;
  400. int fd, must_swab;
  401. ssize_t ret = ELF_LOAD_FAILED;
  402. uint8_t e_ident[EI_NIDENT];
  403. fd = open(filename, O_RDONLY | O_BINARY);
  404. if (fd < 0) {
  405. perror(filename);
  406. return -1;
  407. }
  408. if (read(fd, e_ident, sizeof(e_ident)) != sizeof(e_ident))
  409. goto fail;
  410. if (e_ident[0] != ELFMAG0 ||
  411. e_ident[1] != ELFMAG1 ||
  412. e_ident[2] != ELFMAG2 ||
  413. e_ident[3] != ELFMAG3) {
  414. ret = ELF_LOAD_NOT_ELF;
  415. goto fail;
  416. }
  417. if (elf_data_order != ELFDATANONE && elf_data_order != e_ident[EI_DATA]) {
  418. ret = ELF_LOAD_WRONG_ENDIAN;
  419. goto fail;
  420. }
  421. must_swab = host_data_order != e_ident[EI_DATA];
  422. lseek(fd, 0, SEEK_SET);
  423. if (e_ident[EI_CLASS] == ELFCLASS64) {
  424. ret = load_elf64(filename, fd, elf_note_fn,
  425. translate_fn, translate_opaque, must_swab,
  426. pentry, lowaddr, highaddr, pflags, elf_machine,
  427. clear_lsb, data_swab, as, load_rom, sym_cb);
  428. } else {
  429. ret = load_elf32(filename, fd, elf_note_fn,
  430. translate_fn, translate_opaque, must_swab,
  431. pentry, lowaddr, highaddr, pflags, elf_machine,
  432. clear_lsb, data_swab, as, load_rom, sym_cb);
  433. }
  434. if (ret > 0) {
  435. debuginfo_report_elf(filename, fd, 0);
  436. }
  437. fail:
  438. close(fd);
  439. return ret;
  440. }
  441. static void bswap_uboot_header(uboot_image_header_t *hdr)
  442. {
  443. #if !HOST_BIG_ENDIAN
  444. bswap32s(&hdr->ih_magic);
  445. bswap32s(&hdr->ih_hcrc);
  446. bswap32s(&hdr->ih_time);
  447. bswap32s(&hdr->ih_size);
  448. bswap32s(&hdr->ih_load);
  449. bswap32s(&hdr->ih_ep);
  450. bswap32s(&hdr->ih_dcrc);
  451. #endif
  452. }
  453. #define ZALLOC_ALIGNMENT 16
  454. static void *zalloc(void *x, unsigned items, unsigned size)
  455. {
  456. void *p;
  457. size *= items;
  458. size = (size + ZALLOC_ALIGNMENT - 1) & ~(ZALLOC_ALIGNMENT - 1);
  459. p = g_malloc(size);
  460. return (p);
  461. }
  462. static void zfree(void *x, void *addr)
  463. {
  464. g_free(addr);
  465. }
  466. #define HEAD_CRC 2
  467. #define EXTRA_FIELD 4
  468. #define ORIG_NAME 8
  469. #define COMMENT 0x10
  470. #define RESERVED 0xe0
  471. #define DEFLATED 8
  472. ssize_t gunzip(void *dst, size_t dstlen, uint8_t *src, size_t srclen)
  473. {
  474. z_stream s = {};
  475. ssize_t dstbytes;
  476. int r, i, flags;
  477. /* skip header */
  478. i = 10;
  479. if (srclen < 4) {
  480. goto toosmall;
  481. }
  482. flags = src[3];
  483. if (src[2] != DEFLATED || (flags & RESERVED) != 0) {
  484. puts ("Error: Bad gzipped data\n");
  485. return -1;
  486. }
  487. if ((flags & EXTRA_FIELD) != 0) {
  488. if (srclen < 12) {
  489. goto toosmall;
  490. }
  491. i = 12 + src[10] + (src[11] << 8);
  492. }
  493. if ((flags & ORIG_NAME) != 0) {
  494. while (i < srclen && src[i++] != 0) {
  495. /* do nothing */
  496. }
  497. }
  498. if ((flags & COMMENT) != 0) {
  499. while (i < srclen && src[i++] != 0) {
  500. /* do nothing */
  501. }
  502. }
  503. if ((flags & HEAD_CRC) != 0) {
  504. i += 2;
  505. }
  506. if (i >= srclen) {
  507. goto toosmall;
  508. }
  509. s.zalloc = zalloc;
  510. s.zfree = zfree;
  511. r = inflateInit2(&s, -MAX_WBITS);
  512. if (r != Z_OK) {
  513. printf ("Error: inflateInit2() returned %d\n", r);
  514. return (-1);
  515. }
  516. s.next_in = src + i;
  517. s.avail_in = srclen - i;
  518. s.next_out = dst;
  519. s.avail_out = dstlen;
  520. r = inflate(&s, Z_FINISH);
  521. if (r != Z_OK && r != Z_STREAM_END) {
  522. printf ("Error: inflate() returned %d\n", r);
  523. inflateEnd(&s);
  524. return -1;
  525. }
  526. dstbytes = s.next_out - (unsigned char *) dst;
  527. inflateEnd(&s);
  528. return dstbytes;
  529. toosmall:
  530. puts("Error: gunzip out of data in header\n");
  531. return -1;
  532. }
  533. /* Load a U-Boot image. */
  534. static ssize_t load_uboot_image(const char *filename, hwaddr *ep,
  535. hwaddr *loadaddr, int *is_linux,
  536. uint8_t image_type,
  537. uint64_t (*translate_fn)(void *, uint64_t),
  538. void *translate_opaque, AddressSpace *as)
  539. {
  540. int fd;
  541. ssize_t size;
  542. hwaddr address;
  543. uboot_image_header_t h;
  544. uboot_image_header_t *hdr = &h;
  545. uint8_t *data = NULL;
  546. int ret = -1;
  547. int do_uncompress = 0;
  548. fd = open(filename, O_RDONLY | O_BINARY);
  549. if (fd < 0)
  550. return -1;
  551. size = read(fd, hdr, sizeof(uboot_image_header_t));
  552. if (size < sizeof(uboot_image_header_t)) {
  553. goto out;
  554. }
  555. bswap_uboot_header(hdr);
  556. if (hdr->ih_magic != IH_MAGIC)
  557. goto out;
  558. if (hdr->ih_type != image_type) {
  559. if (!(image_type == IH_TYPE_KERNEL &&
  560. hdr->ih_type == IH_TYPE_KERNEL_NOLOAD)) {
  561. fprintf(stderr, "Wrong image type %d, expected %d\n", hdr->ih_type,
  562. image_type);
  563. goto out;
  564. }
  565. }
  566. /* TODO: Implement other image types. */
  567. switch (hdr->ih_type) {
  568. case IH_TYPE_KERNEL_NOLOAD:
  569. if (!loadaddr || *loadaddr == LOAD_UIMAGE_LOADADDR_INVALID) {
  570. fprintf(stderr, "this image format (kernel_noload) cannot be "
  571. "loaded on this machine type");
  572. goto out;
  573. }
  574. hdr->ih_load = *loadaddr + sizeof(*hdr);
  575. hdr->ih_ep += hdr->ih_load;
  576. /* fall through */
  577. case IH_TYPE_KERNEL:
  578. address = hdr->ih_load;
  579. if (translate_fn) {
  580. address = translate_fn(translate_opaque, address);
  581. }
  582. if (loadaddr) {
  583. *loadaddr = hdr->ih_load;
  584. }
  585. switch (hdr->ih_comp) {
  586. case IH_COMP_NONE:
  587. break;
  588. case IH_COMP_GZIP:
  589. do_uncompress = 1;
  590. break;
  591. default:
  592. fprintf(stderr,
  593. "Unable to load u-boot images with compression type %d\n",
  594. hdr->ih_comp);
  595. goto out;
  596. }
  597. if (ep) {
  598. *ep = hdr->ih_ep;
  599. }
  600. /* TODO: Check CPU type. */
  601. if (is_linux) {
  602. if (hdr->ih_os == IH_OS_LINUX) {
  603. *is_linux = 1;
  604. } else if (hdr->ih_os == IH_OS_VXWORKS) {
  605. /*
  606. * VxWorks 7 uses the same boot interface as the Linux kernel
  607. * on Arm (64-bit only), PowerPC and RISC-V architectures.
  608. */
  609. switch (hdr->ih_arch) {
  610. case IH_ARCH_ARM64:
  611. case IH_ARCH_PPC:
  612. case IH_ARCH_RISCV:
  613. *is_linux = 1;
  614. break;
  615. default:
  616. *is_linux = 0;
  617. break;
  618. }
  619. } else {
  620. *is_linux = 0;
  621. }
  622. }
  623. break;
  624. case IH_TYPE_RAMDISK:
  625. address = *loadaddr;
  626. break;
  627. default:
  628. fprintf(stderr, "Unsupported u-boot image type %d\n", hdr->ih_type);
  629. goto out;
  630. }
  631. data = g_malloc(hdr->ih_size);
  632. if (read(fd, data, hdr->ih_size) != hdr->ih_size) {
  633. fprintf(stderr, "Error reading file\n");
  634. goto out;
  635. }
  636. if (do_uncompress) {
  637. uint8_t *compressed_data;
  638. size_t max_bytes;
  639. ssize_t bytes;
  640. compressed_data = data;
  641. max_bytes = UBOOT_MAX_GUNZIP_BYTES;
  642. data = g_malloc(max_bytes);
  643. bytes = gunzip(data, max_bytes, compressed_data, hdr->ih_size);
  644. g_free(compressed_data);
  645. if (bytes < 0) {
  646. fprintf(stderr, "Unable to decompress gzipped image!\n");
  647. goto out;
  648. }
  649. hdr->ih_size = bytes;
  650. }
  651. rom_add_blob_fixed_as(filename, data, hdr->ih_size, address, as);
  652. ret = hdr->ih_size;
  653. out:
  654. g_free(data);
  655. close(fd);
  656. return ret;
  657. }
  658. ssize_t load_uimage(const char *filename, hwaddr *ep, hwaddr *loadaddr,
  659. int *is_linux,
  660. uint64_t (*translate_fn)(void *, uint64_t),
  661. void *translate_opaque)
  662. {
  663. return load_uboot_image(filename, ep, loadaddr, is_linux, IH_TYPE_KERNEL,
  664. translate_fn, translate_opaque, NULL);
  665. }
  666. ssize_t load_uimage_as(const char *filename, hwaddr *ep, hwaddr *loadaddr,
  667. int *is_linux,
  668. uint64_t (*translate_fn)(void *, uint64_t),
  669. void *translate_opaque, AddressSpace *as)
  670. {
  671. return load_uboot_image(filename, ep, loadaddr, is_linux, IH_TYPE_KERNEL,
  672. translate_fn, translate_opaque, as);
  673. }
  674. /* Load a ramdisk. */
  675. ssize_t load_ramdisk(const char *filename, hwaddr addr, uint64_t max_sz)
  676. {
  677. return load_ramdisk_as(filename, addr, max_sz, NULL);
  678. }
  679. ssize_t load_ramdisk_as(const char *filename, hwaddr addr, uint64_t max_sz,
  680. AddressSpace *as)
  681. {
  682. return load_uboot_image(filename, NULL, &addr, NULL, IH_TYPE_RAMDISK,
  683. NULL, NULL, as);
  684. }
  685. /* Load a gzip-compressed kernel to a dynamically allocated buffer. */
  686. ssize_t load_image_gzipped_buffer(const char *filename, uint64_t max_sz,
  687. uint8_t **buffer)
  688. {
  689. uint8_t *compressed_data = NULL;
  690. uint8_t *data = NULL;
  691. gsize len;
  692. ssize_t bytes;
  693. int ret = -1;
  694. if (!g_file_get_contents(filename, (char **) &compressed_data, &len,
  695. NULL)) {
  696. goto out;
  697. }
  698. /* Is it a gzip-compressed file? */
  699. if (len < 2 ||
  700. compressed_data[0] != 0x1f ||
  701. compressed_data[1] != 0x8b) {
  702. goto out;
  703. }
  704. if (max_sz > LOAD_IMAGE_MAX_GUNZIP_BYTES) {
  705. max_sz = LOAD_IMAGE_MAX_GUNZIP_BYTES;
  706. }
  707. data = g_malloc(max_sz);
  708. bytes = gunzip(data, max_sz, compressed_data, len);
  709. if (bytes < 0) {
  710. fprintf(stderr, "%s: unable to decompress gzipped kernel file\n",
  711. filename);
  712. goto out;
  713. }
  714. /* trim to actual size and return to caller */
  715. *buffer = g_realloc(data, bytes);
  716. ret = bytes;
  717. /* ownership has been transferred to caller */
  718. data = NULL;
  719. out:
  720. g_free(compressed_data);
  721. g_free(data);
  722. return ret;
  723. }
  724. /* The PE/COFF MS-DOS stub magic number */
  725. #define EFI_PE_MSDOS_MAGIC "MZ"
  726. /*
  727. * The Linux header magic number for a EFI PE/COFF
  728. * image targeting an unspecified architecture.
  729. */
  730. #define EFI_PE_LINUX_MAGIC "\xcd\x23\x82\x81"
  731. /*
  732. * Bootable Linux kernel images may be packaged as EFI zboot images, which are
  733. * self-decompressing executables when loaded via EFI. The compressed payload
  734. * can also be extracted from the image and decompressed by a non-EFI loader.
  735. *
  736. * The de facto specification for this format is at the following URL:
  737. *
  738. * https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/drivers/firmware/efi/libstub/zboot-header.S
  739. *
  740. * This definition is based on Linux upstream commit 29636a5ce87beba.
  741. */
  742. struct linux_efi_zboot_header {
  743. uint8_t msdos_magic[2]; /* PE/COFF 'MZ' magic number */
  744. uint8_t reserved0[2];
  745. uint8_t zimg[4]; /* "zimg" for Linux EFI zboot images */
  746. uint32_t payload_offset; /* LE offset to compressed payload */
  747. uint32_t payload_size; /* LE size of the compressed payload */
  748. uint8_t reserved1[8];
  749. char compression_type[32]; /* Compression type, NUL terminated */
  750. uint8_t linux_magic[4]; /* Linux header magic */
  751. uint32_t pe_header_offset; /* LE offset to the PE header */
  752. };
  753. /*
  754. * Check whether *buffer points to a Linux EFI zboot image in memory.
  755. *
  756. * If it does, attempt to decompress it to a new buffer, and free the old one.
  757. * If any of this fails, return an error to the caller.
  758. *
  759. * If the image is not a Linux EFI zboot image, do nothing and return success.
  760. */
  761. ssize_t unpack_efi_zboot_image(uint8_t **buffer, ssize_t *size)
  762. {
  763. const struct linux_efi_zboot_header *header;
  764. uint8_t *data = NULL;
  765. ssize_t ploff, plsize;
  766. ssize_t bytes;
  767. /* ignore if this is too small to be a EFI zboot image */
  768. if (*size < sizeof(*header)) {
  769. return 0;
  770. }
  771. header = (struct linux_efi_zboot_header *)*buffer;
  772. /* ignore if this is not a Linux EFI zboot image */
  773. if (memcmp(&header->msdos_magic, EFI_PE_MSDOS_MAGIC, 2) != 0 ||
  774. memcmp(&header->zimg, "zimg", 4) != 0 ||
  775. memcmp(&header->linux_magic, EFI_PE_LINUX_MAGIC, 4) != 0) {
  776. return 0;
  777. }
  778. if (strcmp(header->compression_type, "gzip") != 0) {
  779. fprintf(stderr,
  780. "unable to handle EFI zboot image with \"%.*s\" compression\n",
  781. (int)sizeof(header->compression_type) - 1,
  782. header->compression_type);
  783. return -1;
  784. }
  785. ploff = ldl_le_p(&header->payload_offset);
  786. plsize = ldl_le_p(&header->payload_size);
  787. if (ploff < 0 || plsize < 0 || ploff + plsize > *size) {
  788. fprintf(stderr, "unable to handle corrupt EFI zboot image\n");
  789. return -1;
  790. }
  791. data = g_malloc(LOAD_IMAGE_MAX_GUNZIP_BYTES);
  792. bytes = gunzip(data, LOAD_IMAGE_MAX_GUNZIP_BYTES, *buffer + ploff, plsize);
  793. if (bytes < 0) {
  794. fprintf(stderr, "failed to decompress EFI zboot image\n");
  795. g_free(data);
  796. return -1;
  797. }
  798. g_free(*buffer);
  799. *buffer = g_realloc(data, bytes);
  800. *size = bytes;
  801. return bytes;
  802. }
  803. /*
  804. * Functions for reboot-persistent memory regions.
  805. * - used for vga bios and option roms.
  806. * - also linux kernel (-kernel / -initrd).
  807. */
  808. typedef struct Rom Rom;
  809. struct Rom {
  810. char *name;
  811. char *path;
  812. /* datasize is the amount of memory allocated in "data". If datasize is less
  813. * than romsize, it means that the area from datasize to romsize is filled
  814. * with zeros.
  815. */
  816. size_t romsize;
  817. size_t datasize;
  818. uint8_t *data;
  819. MemoryRegion *mr;
  820. AddressSpace *as;
  821. int isrom;
  822. char *fw_dir;
  823. char *fw_file;
  824. GMappedFile *mapped_file;
  825. bool committed;
  826. hwaddr addr;
  827. QTAILQ_ENTRY(Rom) next;
  828. };
  829. static FWCfgState *fw_cfg;
  830. static QTAILQ_HEAD(, Rom) roms = QTAILQ_HEAD_INITIALIZER(roms);
  831. /*
  832. * rom->data can be heap-allocated or memory-mapped (e.g. when added with
  833. * rom_add_elf_program())
  834. */
  835. static void rom_free_data(Rom *rom)
  836. {
  837. if (rom->mapped_file) {
  838. g_mapped_file_unref(rom->mapped_file);
  839. rom->mapped_file = NULL;
  840. } else {
  841. g_free(rom->data);
  842. }
  843. rom->data = NULL;
  844. }
  845. static void rom_free(Rom *rom)
  846. {
  847. rom_free_data(rom);
  848. g_free(rom->path);
  849. g_free(rom->name);
  850. g_free(rom->fw_dir);
  851. g_free(rom->fw_file);
  852. g_free(rom);
  853. }
  854. static inline bool rom_order_compare(Rom *rom, Rom *item)
  855. {
  856. return ((uintptr_t)(void *)rom->as > (uintptr_t)(void *)item->as) ||
  857. (rom->as == item->as && rom->addr >= item->addr);
  858. }
  859. static void rom_insert(Rom *rom)
  860. {
  861. Rom *item;
  862. if (roms_loaded) {
  863. hw_error ("ROM images must be loaded at startup\n");
  864. }
  865. /* The user didn't specify an address space, this is the default */
  866. if (!rom->as) {
  867. rom->as = &address_space_memory;
  868. }
  869. rom->committed = false;
  870. /* List is ordered by load address in the same address space */
  871. QTAILQ_FOREACH(item, &roms, next) {
  872. if (rom_order_compare(rom, item)) {
  873. continue;
  874. }
  875. QTAILQ_INSERT_BEFORE(item, rom, next);
  876. return;
  877. }
  878. QTAILQ_INSERT_TAIL(&roms, rom, next);
  879. }
  880. static void fw_cfg_resized(const char *id, uint64_t length, void *host)
  881. {
  882. if (fw_cfg) {
  883. fw_cfg_modify_file(fw_cfg, id + strlen("/rom@"), host, length);
  884. }
  885. }
  886. static void *rom_set_mr(Rom *rom, Object *owner, const char *name, bool ro)
  887. {
  888. void *data;
  889. rom->mr = g_malloc(sizeof(*rom->mr));
  890. memory_region_init_resizeable_ram(rom->mr, owner, name,
  891. rom->datasize, rom->romsize,
  892. fw_cfg_resized,
  893. &error_fatal);
  894. memory_region_set_readonly(rom->mr, ro);
  895. vmstate_register_ram_global(rom->mr);
  896. data = memory_region_get_ram_ptr(rom->mr);
  897. memcpy(data, rom->data, rom->datasize);
  898. return data;
  899. }
  900. ssize_t rom_add_file(const char *file, const char *fw_dir,
  901. hwaddr addr, int32_t bootindex,
  902. bool has_option_rom, MemoryRegion *mr,
  903. AddressSpace *as)
  904. {
  905. MachineClass *mc = MACHINE_GET_CLASS(qdev_get_machine());
  906. Rom *rom;
  907. gsize size;
  908. g_autoptr(GError) gerr = NULL;
  909. char devpath[100];
  910. if (as && mr) {
  911. fprintf(stderr, "Specifying an Address Space and Memory Region is " \
  912. "not valid when loading a rom\n");
  913. /* We haven't allocated anything so we don't need any cleanup */
  914. return -1;
  915. }
  916. rom = g_malloc0(sizeof(*rom));
  917. rom->name = g_strdup(file);
  918. rom->path = qemu_find_file(QEMU_FILE_TYPE_BIOS, rom->name);
  919. rom->as = as;
  920. if (rom->path == NULL) {
  921. rom->path = g_strdup(file);
  922. }
  923. if (!g_file_get_contents(rom->path, (gchar **) &rom->data,
  924. &size, &gerr)) {
  925. fprintf(stderr, "rom: file %-20s: error %s\n",
  926. rom->name, gerr->message);
  927. goto err;
  928. }
  929. if (fw_dir) {
  930. rom->fw_dir = g_strdup(fw_dir);
  931. rom->fw_file = g_strdup(file);
  932. }
  933. rom->addr = addr;
  934. rom->romsize = size;
  935. rom->datasize = rom->romsize;
  936. rom_insert(rom);
  937. if (rom->fw_file && fw_cfg) {
  938. const char *basename;
  939. char fw_file_name[FW_CFG_MAX_FILE_PATH];
  940. void *data;
  941. basename = strrchr(rom->fw_file, '/');
  942. if (basename) {
  943. basename++;
  944. } else {
  945. basename = rom->fw_file;
  946. }
  947. snprintf(fw_file_name, sizeof(fw_file_name), "%s/%s", rom->fw_dir,
  948. basename);
  949. snprintf(devpath, sizeof(devpath), "/rom@%s", fw_file_name);
  950. if ((!has_option_rom || mc->option_rom_has_mr) && mc->rom_file_has_mr) {
  951. data = rom_set_mr(rom, OBJECT(fw_cfg), devpath, true);
  952. } else {
  953. data = rom->data;
  954. }
  955. fw_cfg_add_file(fw_cfg, fw_file_name, data, rom->romsize);
  956. } else {
  957. if (mr) {
  958. rom->mr = mr;
  959. snprintf(devpath, sizeof(devpath), "/rom@%s", file);
  960. } else {
  961. snprintf(devpath, sizeof(devpath), "/rom@" HWADDR_FMT_plx, addr);
  962. }
  963. }
  964. add_boot_device_path(bootindex, NULL, devpath);
  965. return 0;
  966. err:
  967. rom_free(rom);
  968. return -1;
  969. }
  970. MemoryRegion *rom_add_blob(const char *name, const void *blob, size_t len,
  971. size_t max_len, hwaddr addr, const char *fw_file_name,
  972. FWCfgCallback fw_callback, void *callback_opaque,
  973. AddressSpace *as, bool read_only)
  974. {
  975. MachineClass *mc = MACHINE_GET_CLASS(qdev_get_machine());
  976. Rom *rom;
  977. MemoryRegion *mr = NULL;
  978. rom = g_malloc0(sizeof(*rom));
  979. rom->name = g_strdup(name);
  980. rom->as = as;
  981. rom->addr = addr;
  982. rom->romsize = max_len ? max_len : len;
  983. rom->datasize = len;
  984. g_assert(rom->romsize >= rom->datasize);
  985. rom->data = g_malloc0(rom->datasize);
  986. memcpy(rom->data, blob, len);
  987. rom_insert(rom);
  988. if (fw_file_name && fw_cfg) {
  989. char devpath[100];
  990. void *data;
  991. if (read_only) {
  992. snprintf(devpath, sizeof(devpath), "/rom@%s", fw_file_name);
  993. } else {
  994. snprintf(devpath, sizeof(devpath), "/ram@%s", fw_file_name);
  995. }
  996. if (mc->rom_file_has_mr) {
  997. data = rom_set_mr(rom, OBJECT(fw_cfg), devpath, read_only);
  998. mr = rom->mr;
  999. } else {
  1000. data = rom->data;
  1001. }
  1002. fw_cfg_add_file_callback(fw_cfg, fw_file_name,
  1003. fw_callback, NULL, callback_opaque,
  1004. data, rom->datasize, read_only);
  1005. }
  1006. return mr;
  1007. }
  1008. /* This function is specific for elf program because we don't need to allocate
  1009. * all the rom. We just allocate the first part and the rest is just zeros. This
  1010. * is why romsize and datasize are different. Also, this function takes its own
  1011. * reference to "mapped_file", so we don't have to allocate and copy the buffer.
  1012. */
  1013. int rom_add_elf_program(const char *name, GMappedFile *mapped_file, void *data,
  1014. size_t datasize, size_t romsize, hwaddr addr,
  1015. AddressSpace *as)
  1016. {
  1017. Rom *rom;
  1018. rom = g_malloc0(sizeof(*rom));
  1019. rom->name = g_strdup(name);
  1020. rom->addr = addr;
  1021. rom->datasize = datasize;
  1022. rom->romsize = romsize;
  1023. rom->data = data;
  1024. rom->as = as;
  1025. if (mapped_file && data) {
  1026. g_mapped_file_ref(mapped_file);
  1027. rom->mapped_file = mapped_file;
  1028. }
  1029. rom_insert(rom);
  1030. return 0;
  1031. }
  1032. ssize_t rom_add_vga(const char *file)
  1033. {
  1034. return rom_add_file(file, "vgaroms", 0, -1, true, NULL, NULL);
  1035. }
  1036. ssize_t rom_add_option(const char *file, int32_t bootindex)
  1037. {
  1038. return rom_add_file(file, "genroms", 0, bootindex, true, NULL, NULL);
  1039. }
  1040. static void rom_reset(void *unused)
  1041. {
  1042. Rom *rom;
  1043. QTAILQ_FOREACH(rom, &roms, next) {
  1044. if (rom->fw_file) {
  1045. continue;
  1046. }
  1047. /*
  1048. * We don't need to fill in the RAM with ROM data because we'll fill
  1049. * the data in during the next incoming migration in all cases. Note
  1050. * that some of those RAMs can actually be modified by the guest.
  1051. */
  1052. if (runstate_check(RUN_STATE_INMIGRATE)) {
  1053. if (rom->data && rom->isrom) {
  1054. /*
  1055. * Free it so that a rom_reset after migration doesn't
  1056. * overwrite a potentially modified 'rom'.
  1057. */
  1058. rom_free_data(rom);
  1059. }
  1060. continue;
  1061. }
  1062. if (rom->data == NULL) {
  1063. continue;
  1064. }
  1065. if (rom->mr) {
  1066. void *host = memory_region_get_ram_ptr(rom->mr);
  1067. memcpy(host, rom->data, rom->datasize);
  1068. memset(host + rom->datasize, 0, rom->romsize - rom->datasize);
  1069. } else {
  1070. address_space_write_rom(rom->as, rom->addr, MEMTXATTRS_UNSPECIFIED,
  1071. rom->data, rom->datasize);
  1072. address_space_set(rom->as, rom->addr + rom->datasize, 0,
  1073. rom->romsize - rom->datasize,
  1074. MEMTXATTRS_UNSPECIFIED);
  1075. }
  1076. if (rom->isrom) {
  1077. /* rom needs to be written only once */
  1078. rom_free_data(rom);
  1079. }
  1080. /*
  1081. * The rom loader is really on the same level as firmware in the guest
  1082. * shadowing a ROM into RAM. Such a shadowing mechanism needs to ensure
  1083. * that the instruction cache for that new region is clear, so that the
  1084. * CPU definitely fetches its instructions from the just written data.
  1085. */
  1086. cpu_flush_icache_range(rom->addr, rom->datasize);
  1087. trace_loader_write_rom(rom->name, rom->addr, rom->datasize, rom->isrom);
  1088. }
  1089. }
  1090. /* Return true if two consecutive ROMs in the ROM list overlap */
  1091. static bool roms_overlap(Rom *last_rom, Rom *this_rom)
  1092. {
  1093. if (!last_rom) {
  1094. return false;
  1095. }
  1096. return last_rom->as == this_rom->as &&
  1097. last_rom->addr + last_rom->romsize > this_rom->addr;
  1098. }
  1099. static const char *rom_as_name(Rom *rom)
  1100. {
  1101. const char *name = rom->as ? rom->as->name : NULL;
  1102. return name ?: "anonymous";
  1103. }
  1104. static void rom_print_overlap_error_header(void)
  1105. {
  1106. error_report("Some ROM regions are overlapping");
  1107. error_printf(
  1108. "These ROM regions might have been loaded by "
  1109. "direct user request or by default.\n"
  1110. "They could be BIOS/firmware images, a guest kernel, "
  1111. "initrd or some other file loaded into guest memory.\n"
  1112. "Check whether you intended to load all this guest code, and "
  1113. "whether it has been built to load to the correct addresses.\n");
  1114. }
  1115. static void rom_print_one_overlap_error(Rom *last_rom, Rom *rom)
  1116. {
  1117. error_printf(
  1118. "\nThe following two regions overlap (in the %s address space):\n",
  1119. rom_as_name(rom));
  1120. error_printf(
  1121. " %s (addresses 0x" HWADDR_FMT_plx " - 0x" HWADDR_FMT_plx ")\n",
  1122. last_rom->name, last_rom->addr, last_rom->addr + last_rom->romsize);
  1123. error_printf(
  1124. " %s (addresses 0x" HWADDR_FMT_plx " - 0x" HWADDR_FMT_plx ")\n",
  1125. rom->name, rom->addr, rom->addr + rom->romsize);
  1126. }
  1127. int rom_check_and_register_reset(void)
  1128. {
  1129. MemoryRegionSection section;
  1130. Rom *rom, *last_rom = NULL;
  1131. bool found_overlap = false;
  1132. QTAILQ_FOREACH(rom, &roms, next) {
  1133. if (rom->fw_file) {
  1134. continue;
  1135. }
  1136. if (!rom->mr) {
  1137. if (roms_overlap(last_rom, rom)) {
  1138. if (!found_overlap) {
  1139. found_overlap = true;
  1140. rom_print_overlap_error_header();
  1141. }
  1142. rom_print_one_overlap_error(last_rom, rom);
  1143. /* Keep going through the list so we report all overlaps */
  1144. }
  1145. last_rom = rom;
  1146. }
  1147. section = memory_region_find(rom->mr ? rom->mr : get_system_memory(),
  1148. rom->addr, 1);
  1149. rom->isrom = int128_nz(section.size) && memory_region_is_rom(section.mr);
  1150. memory_region_unref(section.mr);
  1151. }
  1152. if (found_overlap) {
  1153. return -1;
  1154. }
  1155. qemu_register_reset(rom_reset, NULL);
  1156. roms_loaded = 1;
  1157. return 0;
  1158. }
  1159. void rom_set_fw(FWCfgState *f)
  1160. {
  1161. fw_cfg = f;
  1162. }
  1163. void rom_set_order_override(int order)
  1164. {
  1165. if (!fw_cfg)
  1166. return;
  1167. fw_cfg_set_order_override(fw_cfg, order);
  1168. }
  1169. void rom_reset_order_override(void)
  1170. {
  1171. if (!fw_cfg)
  1172. return;
  1173. fw_cfg_reset_order_override(fw_cfg);
  1174. }
  1175. void rom_transaction_begin(void)
  1176. {
  1177. Rom *rom;
  1178. /* Ignore ROMs added without the transaction API */
  1179. QTAILQ_FOREACH(rom, &roms, next) {
  1180. rom->committed = true;
  1181. }
  1182. }
  1183. void rom_transaction_end(bool commit)
  1184. {
  1185. Rom *rom;
  1186. Rom *tmp;
  1187. QTAILQ_FOREACH_SAFE(rom, &roms, next, tmp) {
  1188. if (rom->committed) {
  1189. continue;
  1190. }
  1191. if (commit) {
  1192. rom->committed = true;
  1193. } else {
  1194. QTAILQ_REMOVE(&roms, rom, next);
  1195. rom_free(rom);
  1196. }
  1197. }
  1198. }
  1199. static Rom *find_rom(hwaddr addr, size_t size)
  1200. {
  1201. Rom *rom;
  1202. QTAILQ_FOREACH(rom, &roms, next) {
  1203. if (rom->fw_file) {
  1204. continue;
  1205. }
  1206. if (rom->mr) {
  1207. continue;
  1208. }
  1209. if (rom->addr > addr) {
  1210. continue;
  1211. }
  1212. if (rom->addr + rom->romsize < addr + size) {
  1213. continue;
  1214. }
  1215. return rom;
  1216. }
  1217. return NULL;
  1218. }
  1219. typedef struct RomSec {
  1220. hwaddr base;
  1221. int se; /* start/end flag */
  1222. } RomSec;
  1223. /*
  1224. * Sort into address order. We break ties between rom-startpoints
  1225. * and rom-endpoints in favour of the startpoint, by sorting the 0->1
  1226. * transition before the 1->0 transition. Either way round would
  1227. * work, but this way saves a little work later by avoiding
  1228. * dealing with "gaps" of 0 length.
  1229. */
  1230. static gint sort_secs(gconstpointer a, gconstpointer b)
  1231. {
  1232. RomSec *ra = (RomSec *) a;
  1233. RomSec *rb = (RomSec *) b;
  1234. if (ra->base == rb->base) {
  1235. return ra->se - rb->se;
  1236. }
  1237. return ra->base > rb->base ? 1 : -1;
  1238. }
  1239. static GList *add_romsec_to_list(GList *secs, hwaddr base, int se)
  1240. {
  1241. RomSec *cand = g_new(RomSec, 1);
  1242. cand->base = base;
  1243. cand->se = se;
  1244. return g_list_prepend(secs, cand);
  1245. }
  1246. RomGap rom_find_largest_gap_between(hwaddr base, size_t size)
  1247. {
  1248. Rom *rom;
  1249. RomSec *cand;
  1250. RomGap res = {0, 0};
  1251. hwaddr gapstart = base;
  1252. GList *it, *secs = NULL;
  1253. int count = 0;
  1254. QTAILQ_FOREACH(rom, &roms, next) {
  1255. /* Ignore blobs being loaded to special places */
  1256. if (rom->mr || rom->fw_file) {
  1257. continue;
  1258. }
  1259. /* ignore anything finishing below base */
  1260. if (rom->addr + rom->romsize <= base) {
  1261. continue;
  1262. }
  1263. /* ignore anything starting above the region */
  1264. if (rom->addr >= base + size) {
  1265. continue;
  1266. }
  1267. /* Save the start and end of each relevant ROM */
  1268. secs = add_romsec_to_list(secs, rom->addr, 1);
  1269. if (rom->addr + rom->romsize < base + size) {
  1270. secs = add_romsec_to_list(secs, rom->addr + rom->romsize, -1);
  1271. }
  1272. }
  1273. /* sentinel */
  1274. secs = add_romsec_to_list(secs, base + size, 1);
  1275. secs = g_list_sort(secs, sort_secs);
  1276. for (it = g_list_first(secs); it; it = g_list_next(it)) {
  1277. cand = (RomSec *) it->data;
  1278. if (count == 0 && count + cand->se == 1) {
  1279. size_t gap = cand->base - gapstart;
  1280. if (gap > res.size) {
  1281. res.base = gapstart;
  1282. res.size = gap;
  1283. }
  1284. } else if (count == 1 && count + cand->se == 0) {
  1285. gapstart = cand->base;
  1286. }
  1287. count += cand->se;
  1288. }
  1289. g_list_free_full(secs, g_free);
  1290. return res;
  1291. }
  1292. /*
  1293. * Copies memory from registered ROMs to dest. Any memory that is contained in
  1294. * a ROM between addr and addr + size is copied. Note that this can involve
  1295. * multiple ROMs, which need not start at addr and need not end at addr + size.
  1296. */
  1297. int rom_copy(uint8_t *dest, hwaddr addr, size_t size)
  1298. {
  1299. hwaddr end = addr + size;
  1300. uint8_t *s, *d = dest;
  1301. size_t l = 0;
  1302. Rom *rom;
  1303. QTAILQ_FOREACH(rom, &roms, next) {
  1304. if (rom->fw_file) {
  1305. continue;
  1306. }
  1307. if (rom->mr) {
  1308. continue;
  1309. }
  1310. if (rom->addr + rom->romsize < addr) {
  1311. continue;
  1312. }
  1313. if (rom->addr > end || rom->addr < addr) {
  1314. break;
  1315. }
  1316. d = dest + (rom->addr - addr);
  1317. s = rom->data;
  1318. l = rom->datasize;
  1319. if ((d + l) > (dest + size)) {
  1320. l = dest - d;
  1321. }
  1322. if (l > 0) {
  1323. memcpy(d, s, l);
  1324. }
  1325. if (rom->romsize > rom->datasize) {
  1326. /* If datasize is less than romsize, it means that we didn't
  1327. * allocate all the ROM because the trailing data are only zeros.
  1328. */
  1329. d += l;
  1330. l = rom->romsize - rom->datasize;
  1331. if ((d + l) > (dest + size)) {
  1332. /* Rom size doesn't fit in the destination area. Adjust to avoid
  1333. * overflow.
  1334. */
  1335. l = dest - d;
  1336. }
  1337. if (l > 0) {
  1338. memset(d, 0x0, l);
  1339. }
  1340. }
  1341. }
  1342. return (d + l) - dest;
  1343. }
  1344. void *rom_ptr(hwaddr addr, size_t size)
  1345. {
  1346. Rom *rom;
  1347. rom = find_rom(addr, size);
  1348. if (!rom || !rom->data)
  1349. return NULL;
  1350. return rom->data + (addr - rom->addr);
  1351. }
  1352. typedef struct FindRomCBData {
  1353. size_t size; /* Amount of data we want from ROM, in bytes */
  1354. MemoryRegion *mr; /* MR at the unaliased guest addr */
  1355. hwaddr xlat; /* Offset of addr within mr */
  1356. void *rom; /* Output: rom data pointer, if found */
  1357. } FindRomCBData;
  1358. static bool find_rom_cb(Int128 start, Int128 len, const MemoryRegion *mr,
  1359. hwaddr offset_in_region, void *opaque)
  1360. {
  1361. FindRomCBData *cbdata = opaque;
  1362. hwaddr alias_addr;
  1363. if (mr != cbdata->mr) {
  1364. return false;
  1365. }
  1366. alias_addr = int128_get64(start) + cbdata->xlat - offset_in_region;
  1367. cbdata->rom = rom_ptr(alias_addr, cbdata->size);
  1368. if (!cbdata->rom) {
  1369. return false;
  1370. }
  1371. /* Found a match, stop iterating */
  1372. return true;
  1373. }
  1374. void *rom_ptr_for_as(AddressSpace *as, hwaddr addr, size_t size)
  1375. {
  1376. /*
  1377. * Find any ROM data for the given guest address range. If there
  1378. * is a ROM blob then return a pointer to the host memory
  1379. * corresponding to 'addr'; otherwise return NULL.
  1380. *
  1381. * We look not only for ROM blobs that were loaded directly to
  1382. * addr, but also for ROM blobs that were loaded to aliases of
  1383. * that memory at other addresses within the AddressSpace.
  1384. *
  1385. * Note that we do not check @as against the 'as' member in the
  1386. * 'struct Rom' returned by rom_ptr(). The Rom::as is the
  1387. * AddressSpace which the rom blob should be written to, whereas
  1388. * our @as argument is the AddressSpace which we are (effectively)
  1389. * reading from, and the same underlying RAM will often be visible
  1390. * in multiple AddressSpaces. (A common example is a ROM blob
  1391. * written to the 'system' address space but then read back via a
  1392. * CPU's cpu->as pointer.) This does mean we might potentially
  1393. * return a false-positive match if a ROM blob was loaded into an
  1394. * AS which is entirely separate and distinct from the one we're
  1395. * querying, but this issue exists also for rom_ptr() and hasn't
  1396. * caused any problems in practice.
  1397. */
  1398. FlatView *fv;
  1399. void *rom;
  1400. hwaddr len_unused;
  1401. FindRomCBData cbdata = {};
  1402. /* Easy case: there's data at the actual address */
  1403. rom = rom_ptr(addr, size);
  1404. if (rom) {
  1405. return rom;
  1406. }
  1407. RCU_READ_LOCK_GUARD();
  1408. fv = address_space_to_flatview(as);
  1409. cbdata.mr = flatview_translate(fv, addr, &cbdata.xlat, &len_unused,
  1410. false, MEMTXATTRS_UNSPECIFIED);
  1411. if (!cbdata.mr) {
  1412. /* Nothing at this address, so there can't be any aliasing */
  1413. return NULL;
  1414. }
  1415. cbdata.size = size;
  1416. flatview_for_each_range(fv, find_rom_cb, &cbdata);
  1417. return cbdata.rom;
  1418. }
  1419. HumanReadableText *qmp_x_query_roms(Error **errp)
  1420. {
  1421. Rom *rom;
  1422. g_autoptr(GString) buf = g_string_new("");
  1423. QTAILQ_FOREACH(rom, &roms, next) {
  1424. if (rom->mr) {
  1425. g_string_append_printf(buf, "%s"
  1426. " size=0x%06zx name=\"%s\"\n",
  1427. memory_region_name(rom->mr),
  1428. rom->romsize,
  1429. rom->name);
  1430. } else if (!rom->fw_file) {
  1431. g_string_append_printf(buf, "addr=" HWADDR_FMT_plx
  1432. " size=0x%06zx mem=%s name=\"%s\"\n",
  1433. rom->addr, rom->romsize,
  1434. rom->isrom ? "rom" : "ram",
  1435. rom->name);
  1436. } else {
  1437. g_string_append_printf(buf, "fw=%s/%s"
  1438. " size=0x%06zx name=\"%s\"\n",
  1439. rom->fw_dir,
  1440. rom->fw_file,
  1441. rom->romsize,
  1442. rom->name);
  1443. }
  1444. }
  1445. return human_readable_text_from_str(buf);
  1446. }
  1447. typedef enum HexRecord HexRecord;
  1448. enum HexRecord {
  1449. DATA_RECORD = 0,
  1450. EOF_RECORD,
  1451. EXT_SEG_ADDR_RECORD,
  1452. START_SEG_ADDR_RECORD,
  1453. EXT_LINEAR_ADDR_RECORD,
  1454. START_LINEAR_ADDR_RECORD,
  1455. };
  1456. /* Each record contains a 16-bit address which is combined with the upper 16
  1457. * bits of the implicit "next address" to form a 32-bit address.
  1458. */
  1459. #define NEXT_ADDR_MASK 0xffff0000
  1460. #define DATA_FIELD_MAX_LEN 0xff
  1461. #define LEN_EXCEPT_DATA 0x5
  1462. /* 0x5 = sizeof(byte_count) + sizeof(address) + sizeof(record_type) +
  1463. * sizeof(checksum) */
  1464. typedef struct {
  1465. uint8_t byte_count;
  1466. uint16_t address;
  1467. uint8_t record_type;
  1468. uint8_t data[DATA_FIELD_MAX_LEN];
  1469. uint8_t checksum;
  1470. } HexLine;
  1471. /* return 0 or -1 if error */
  1472. static bool parse_record(HexLine *line, uint8_t *our_checksum, const uint8_t c,
  1473. uint32_t *index, const bool in_process)
  1474. {
  1475. /* +-------+---------------+-------+---------------------+--------+
  1476. * | byte | |record | | |
  1477. * | count | address | type | data |checksum|
  1478. * +-------+---------------+-------+---------------------+--------+
  1479. * ^ ^ ^ ^ ^ ^
  1480. * |1 byte | 2 bytes |1 byte | 0-255 bytes | 1 byte |
  1481. */
  1482. uint8_t value = 0;
  1483. uint32_t idx = *index;
  1484. /* ignore space */
  1485. if (g_ascii_isspace(c)) {
  1486. return true;
  1487. }
  1488. if (!g_ascii_isxdigit(c) || !in_process) {
  1489. return false;
  1490. }
  1491. value = g_ascii_xdigit_value(c);
  1492. value = (idx & 0x1) ? (value & 0xf) : (value << 4);
  1493. if (idx < 2) {
  1494. line->byte_count |= value;
  1495. } else if (2 <= idx && idx < 6) {
  1496. line->address <<= 4;
  1497. line->address += g_ascii_xdigit_value(c);
  1498. } else if (6 <= idx && idx < 8) {
  1499. line->record_type |= value;
  1500. } else if (8 <= idx && idx < 8 + 2 * line->byte_count) {
  1501. line->data[(idx - 8) >> 1] |= value;
  1502. } else if (8 + 2 * line->byte_count <= idx &&
  1503. idx < 10 + 2 * line->byte_count) {
  1504. line->checksum |= value;
  1505. } else {
  1506. return false;
  1507. }
  1508. *our_checksum += value;
  1509. ++(*index);
  1510. return true;
  1511. }
  1512. typedef struct {
  1513. const char *filename;
  1514. HexLine line;
  1515. uint8_t *bin_buf;
  1516. hwaddr *start_addr;
  1517. int total_size;
  1518. uint32_t next_address_to_write;
  1519. uint32_t current_address;
  1520. uint32_t current_rom_index;
  1521. uint32_t rom_start_address;
  1522. AddressSpace *as;
  1523. bool complete;
  1524. } HexParser;
  1525. /* return size or -1 if error */
  1526. static int handle_record_type(HexParser *parser)
  1527. {
  1528. HexLine *line = &(parser->line);
  1529. switch (line->record_type) {
  1530. case DATA_RECORD:
  1531. parser->current_address =
  1532. (parser->next_address_to_write & NEXT_ADDR_MASK) | line->address;
  1533. /* verify this is a contiguous block of memory */
  1534. if (parser->current_address != parser->next_address_to_write) {
  1535. if (parser->current_rom_index != 0) {
  1536. rom_add_blob_fixed_as(parser->filename, parser->bin_buf,
  1537. parser->current_rom_index,
  1538. parser->rom_start_address, parser->as);
  1539. }
  1540. parser->rom_start_address = parser->current_address;
  1541. parser->current_rom_index = 0;
  1542. }
  1543. /* copy from line buffer to output bin_buf */
  1544. memcpy(parser->bin_buf + parser->current_rom_index, line->data,
  1545. line->byte_count);
  1546. parser->current_rom_index += line->byte_count;
  1547. parser->total_size += line->byte_count;
  1548. /* save next address to write */
  1549. parser->next_address_to_write =
  1550. parser->current_address + line->byte_count;
  1551. break;
  1552. case EOF_RECORD:
  1553. if (parser->current_rom_index != 0) {
  1554. rom_add_blob_fixed_as(parser->filename, parser->bin_buf,
  1555. parser->current_rom_index,
  1556. parser->rom_start_address, parser->as);
  1557. }
  1558. parser->complete = true;
  1559. return parser->total_size;
  1560. case EXT_SEG_ADDR_RECORD:
  1561. case EXT_LINEAR_ADDR_RECORD:
  1562. if (line->byte_count != 2 && line->address != 0) {
  1563. return -1;
  1564. }
  1565. if (parser->current_rom_index != 0) {
  1566. rom_add_blob_fixed_as(parser->filename, parser->bin_buf,
  1567. parser->current_rom_index,
  1568. parser->rom_start_address, parser->as);
  1569. }
  1570. /* save next address to write,
  1571. * in case of non-contiguous block of memory */
  1572. parser->next_address_to_write = (line->data[0] << 12) |
  1573. (line->data[1] << 4);
  1574. if (line->record_type == EXT_LINEAR_ADDR_RECORD) {
  1575. parser->next_address_to_write <<= 12;
  1576. }
  1577. parser->rom_start_address = parser->next_address_to_write;
  1578. parser->current_rom_index = 0;
  1579. break;
  1580. case START_SEG_ADDR_RECORD:
  1581. if (line->byte_count != 4 && line->address != 0) {
  1582. return -1;
  1583. }
  1584. /* x86 16-bit CS:IP segmented addressing */
  1585. *(parser->start_addr) = (((line->data[0] << 8) | line->data[1]) << 4) +
  1586. ((line->data[2] << 8) | line->data[3]);
  1587. break;
  1588. case START_LINEAR_ADDR_RECORD:
  1589. if (line->byte_count != 4 && line->address != 0) {
  1590. return -1;
  1591. }
  1592. *(parser->start_addr) = ldl_be_p(line->data);
  1593. break;
  1594. default:
  1595. return -1;
  1596. }
  1597. return parser->total_size;
  1598. }
  1599. /* return size or -1 if error */
  1600. static int parse_hex_blob(const char *filename, hwaddr *addr, uint8_t *hex_blob,
  1601. size_t hex_blob_size, AddressSpace *as)
  1602. {
  1603. bool in_process = false; /* avoid re-enter and
  1604. * check whether record begin with ':' */
  1605. uint8_t *end = hex_blob + hex_blob_size;
  1606. uint8_t our_checksum = 0;
  1607. uint32_t record_index = 0;
  1608. HexParser parser = {
  1609. .filename = filename,
  1610. .bin_buf = g_malloc(hex_blob_size),
  1611. .start_addr = addr,
  1612. .as = as,
  1613. .complete = false
  1614. };
  1615. rom_transaction_begin();
  1616. for (; hex_blob < end && !parser.complete; ++hex_blob) {
  1617. switch (*hex_blob) {
  1618. case '\r':
  1619. case '\n':
  1620. if (!in_process) {
  1621. break;
  1622. }
  1623. in_process = false;
  1624. if ((LEN_EXCEPT_DATA + parser.line.byte_count) * 2 !=
  1625. record_index ||
  1626. our_checksum != 0) {
  1627. parser.total_size = -1;
  1628. goto out;
  1629. }
  1630. if (handle_record_type(&parser) == -1) {
  1631. parser.total_size = -1;
  1632. goto out;
  1633. }
  1634. break;
  1635. /* start of a new record. */
  1636. case ':':
  1637. memset(&parser.line, 0, sizeof(HexLine));
  1638. in_process = true;
  1639. record_index = 0;
  1640. break;
  1641. /* decoding lines */
  1642. default:
  1643. if (!parse_record(&parser.line, &our_checksum, *hex_blob,
  1644. &record_index, in_process)) {
  1645. parser.total_size = -1;
  1646. goto out;
  1647. }
  1648. break;
  1649. }
  1650. }
  1651. out:
  1652. g_free(parser.bin_buf);
  1653. rom_transaction_end(parser.total_size != -1);
  1654. return parser.total_size;
  1655. }
  1656. /* return size or -1 if error */
  1657. ssize_t load_targphys_hex_as(const char *filename, hwaddr *entry,
  1658. AddressSpace *as)
  1659. {
  1660. gsize hex_blob_size;
  1661. gchar *hex_blob;
  1662. ssize_t total_size = 0;
  1663. if (!g_file_get_contents(filename, &hex_blob, &hex_blob_size, NULL)) {
  1664. return -1;
  1665. }
  1666. total_size = parse_hex_blob(filename, entry, (uint8_t *)hex_blob,
  1667. hex_blob_size, as);
  1668. g_free(hex_blob);
  1669. return total_size;
  1670. }