loader.c 52 KB

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