loader.c 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915
  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/cpr.h"
  54. #include "migration/vmstate.h"
  55. #include "monitor/monitor.h"
  56. #include "system/reset.h"
  57. #include "system/system.h"
  58. #include "uboot_image.h"
  59. #include "hw/loader.h"
  60. #include "hw/nvram/fw_cfg.h"
  61. #include "exec/memory.h"
  62. #include "hw/boards.h"
  63. #include "qemu/cutils.h"
  64. #include "system/runstate.h"
  65. #include "tcg/debuginfo.h"
  66. #include <zlib.h>
  67. static int roms_loaded;
  68. /* return the size or -1 if error */
  69. int64_t get_image_size(const char *filename)
  70. {
  71. int fd;
  72. int64_t size;
  73. fd = open(filename, O_RDONLY | O_BINARY);
  74. if (fd < 0)
  75. return -1;
  76. size = lseek(fd, 0, SEEK_END);
  77. close(fd);
  78. return size;
  79. }
  80. /* return the size or -1 if error */
  81. ssize_t load_image_size(const char *filename, void *addr, size_t size)
  82. {
  83. int fd;
  84. ssize_t actsize, l = 0;
  85. fd = open(filename, O_RDONLY | O_BINARY);
  86. if (fd < 0) {
  87. return -1;
  88. }
  89. while ((actsize = read(fd, addr + l, size - l)) > 0) {
  90. l += actsize;
  91. }
  92. close(fd);
  93. return actsize < 0 ? -1 : l;
  94. }
  95. /* read()-like version */
  96. ssize_t read_targphys(const char *name,
  97. int fd, hwaddr dst_addr, size_t nbytes)
  98. {
  99. uint8_t *buf;
  100. ssize_t did;
  101. buf = g_malloc(nbytes);
  102. did = read(fd, buf, nbytes);
  103. if (did > 0)
  104. rom_add_blob_fixed("read", buf, did, dst_addr);
  105. g_free(buf);
  106. return did;
  107. }
  108. ssize_t load_image_targphys(const char *filename,
  109. hwaddr addr, uint64_t max_sz)
  110. {
  111. return load_image_targphys_as(filename, addr, max_sz, NULL);
  112. }
  113. /* return the size or -1 if error */
  114. ssize_t load_image_targphys_as(const char *filename,
  115. hwaddr addr, uint64_t max_sz, AddressSpace *as)
  116. {
  117. ssize_t size;
  118. size = get_image_size(filename);
  119. if (size < 0 || size > max_sz) {
  120. return -1;
  121. }
  122. if (size > 0) {
  123. if (rom_add_file_fixed_as(filename, addr, -1, as) < 0) {
  124. return -1;
  125. }
  126. }
  127. return size;
  128. }
  129. ssize_t load_image_mr(const char *filename, MemoryRegion *mr)
  130. {
  131. ssize_t size;
  132. if (!memory_access_is_direct(mr, false, MEMTXATTRS_UNSPECIFIED)) {
  133. /* Can only load an image into RAM or ROM */
  134. return -1;
  135. }
  136. size = get_image_size(filename);
  137. if (size < 0 || size > memory_region_size(mr)) {
  138. return -1;
  139. }
  140. if (size > 0) {
  141. if (rom_add_file_mr(filename, mr, -1) < 0) {
  142. return -1;
  143. }
  144. }
  145. return size;
  146. }
  147. void pstrcpy_targphys(const char *name, hwaddr dest, int buf_size,
  148. const char *source)
  149. {
  150. const char *nulp;
  151. char *ptr;
  152. if (buf_size <= 0) return;
  153. nulp = memchr(source, 0, buf_size);
  154. if (nulp) {
  155. rom_add_blob_fixed(name, source, (nulp - source) + 1, dest);
  156. } else {
  157. rom_add_blob_fixed(name, source, buf_size, dest);
  158. ptr = rom_ptr(dest + buf_size - 1, sizeof(*ptr));
  159. *ptr = 0;
  160. }
  161. }
  162. /* A.OUT loader */
  163. struct exec
  164. {
  165. uint32_t a_info; /* Use macros N_MAGIC, etc for access */
  166. uint32_t a_text; /* length of text, in bytes */
  167. uint32_t a_data; /* length of data, in bytes */
  168. uint32_t a_bss; /* length of uninitialized data area, in bytes */
  169. uint32_t a_syms; /* length of symbol table data in file, in bytes */
  170. uint32_t a_entry; /* start address */
  171. uint32_t a_trsize; /* length of relocation info for text, in bytes */
  172. uint32_t a_drsize; /* length of relocation info for data, in bytes */
  173. };
  174. static void bswap_ahdr(struct exec *e)
  175. {
  176. bswap32s(&e->a_info);
  177. bswap32s(&e->a_text);
  178. bswap32s(&e->a_data);
  179. bswap32s(&e->a_bss);
  180. bswap32s(&e->a_syms);
  181. bswap32s(&e->a_entry);
  182. bswap32s(&e->a_trsize);
  183. bswap32s(&e->a_drsize);
  184. }
  185. #define N_MAGIC(exec) ((exec).a_info & 0xffff)
  186. #define OMAGIC 0407
  187. #define NMAGIC 0410
  188. #define ZMAGIC 0413
  189. #define QMAGIC 0314
  190. #define _N_HDROFF(x) (1024 - sizeof (struct exec))
  191. #define N_TXTOFF(x) \
  192. (N_MAGIC(x) == ZMAGIC ? _N_HDROFF((x)) + sizeof (struct exec) : \
  193. (N_MAGIC(x) == QMAGIC ? 0 : sizeof (struct exec)))
  194. #define N_TXTADDR(x, target_page_size) (N_MAGIC(x) == QMAGIC ? target_page_size : 0)
  195. #define _N_SEGMENT_ROUND(x, target_page_size) (((x) + target_page_size - 1) & ~(target_page_size - 1))
  196. #define _N_TXTENDADDR(x, target_page_size) (N_TXTADDR(x, target_page_size)+(x).a_text)
  197. #define N_DATADDR(x, target_page_size) \
  198. (N_MAGIC(x)==OMAGIC? (_N_TXTENDADDR(x, target_page_size)) \
  199. : (_N_SEGMENT_ROUND (_N_TXTENDADDR(x, target_page_size), target_page_size)))
  200. ssize_t load_aout(const char *filename, hwaddr addr, int max_sz,
  201. bool big_endian, hwaddr target_page_size)
  202. {
  203. int fd;
  204. ssize_t size, ret;
  205. struct exec e;
  206. uint32_t magic;
  207. fd = open(filename, O_RDONLY | O_BINARY);
  208. if (fd < 0)
  209. return -1;
  210. size = read(fd, &e, sizeof(e));
  211. if (size < 0)
  212. goto fail;
  213. if (big_endian != HOST_BIG_ENDIAN) {
  214. bswap_ahdr(&e);
  215. }
  216. magic = N_MAGIC(e);
  217. switch (magic) {
  218. case ZMAGIC:
  219. case QMAGIC:
  220. case OMAGIC:
  221. if (e.a_text + e.a_data > max_sz)
  222. goto fail;
  223. lseek(fd, N_TXTOFF(e), SEEK_SET);
  224. size = read_targphys(filename, fd, addr, e.a_text + e.a_data);
  225. if (size < 0)
  226. goto fail;
  227. break;
  228. case NMAGIC:
  229. if (N_DATADDR(e, target_page_size) + e.a_data > max_sz)
  230. goto fail;
  231. lseek(fd, N_TXTOFF(e), SEEK_SET);
  232. size = read_targphys(filename, fd, addr, e.a_text);
  233. if (size < 0)
  234. goto fail;
  235. ret = read_targphys(filename, fd, addr + N_DATADDR(e, target_page_size),
  236. e.a_data);
  237. if (ret < 0)
  238. goto fail;
  239. size += ret;
  240. break;
  241. default:
  242. goto fail;
  243. }
  244. close(fd);
  245. return size;
  246. fail:
  247. close(fd);
  248. return -1;
  249. }
  250. /* ELF loader */
  251. static void *load_at(int fd, off_t offset, size_t size)
  252. {
  253. void *ptr;
  254. if (lseek(fd, offset, SEEK_SET) < 0)
  255. return NULL;
  256. ptr = g_malloc(size);
  257. if (read(fd, ptr, size) != size) {
  258. g_free(ptr);
  259. return NULL;
  260. }
  261. return ptr;
  262. }
  263. #ifdef ELF_CLASS
  264. #undef ELF_CLASS
  265. #endif
  266. #define ELF_CLASS ELFCLASS32
  267. #include "elf.h"
  268. #define SZ 32
  269. #define elf_word uint32_t
  270. #define elf_sword int32_t
  271. #define bswapSZs bswap32s
  272. #include "hw/elf_ops.h.inc"
  273. #undef elfhdr
  274. #undef elf_phdr
  275. #undef elf_shdr
  276. #undef elf_sym
  277. #undef elf_rela
  278. #undef elf_note
  279. #undef elf_word
  280. #undef elf_sword
  281. #undef bswapSZs
  282. #undef SZ
  283. #define elfhdr elf64_hdr
  284. #define elf_phdr elf64_phdr
  285. #define elf_note elf64_note
  286. #define elf_shdr elf64_shdr
  287. #define elf_sym elf64_sym
  288. #define elf_rela elf64_rela
  289. #define elf_word uint64_t
  290. #define elf_sword int64_t
  291. #define bswapSZs bswap64s
  292. #define SZ 64
  293. #include "hw/elf_ops.h.inc"
  294. const char *load_elf_strerror(ssize_t error)
  295. {
  296. switch (error) {
  297. case 0:
  298. return "No error";
  299. case ELF_LOAD_FAILED:
  300. return "Failed to load ELF";
  301. case ELF_LOAD_NOT_ELF:
  302. return "The image is not ELF";
  303. case ELF_LOAD_WRONG_ARCH:
  304. return "The image is from incompatible architecture";
  305. case ELF_LOAD_WRONG_ENDIAN:
  306. return "The image has incorrect endianness";
  307. case ELF_LOAD_TOO_BIG:
  308. return "The image segments are too big to load";
  309. default:
  310. return "Unknown error";
  311. }
  312. }
  313. void load_elf_hdr(const char *filename, void *hdr, bool *is64, Error **errp)
  314. {
  315. int fd;
  316. uint8_t e_ident_local[EI_NIDENT];
  317. uint8_t *e_ident;
  318. size_t hdr_size, off;
  319. bool is64l;
  320. if (!hdr) {
  321. hdr = e_ident_local;
  322. }
  323. e_ident = hdr;
  324. fd = open(filename, O_RDONLY | O_BINARY);
  325. if (fd < 0) {
  326. error_setg_errno(errp, errno, "Failed to open file: %s", filename);
  327. return;
  328. }
  329. if (read(fd, hdr, EI_NIDENT) != EI_NIDENT) {
  330. error_setg_errno(errp, errno, "Failed to read file: %s", filename);
  331. goto fail;
  332. }
  333. if (e_ident[0] != ELFMAG0 ||
  334. e_ident[1] != ELFMAG1 ||
  335. e_ident[2] != ELFMAG2 ||
  336. e_ident[3] != ELFMAG3) {
  337. error_setg(errp, "Bad ELF magic");
  338. goto fail;
  339. }
  340. is64l = e_ident[EI_CLASS] == ELFCLASS64;
  341. hdr_size = is64l ? sizeof(Elf64_Ehdr) : sizeof(Elf32_Ehdr);
  342. if (is64) {
  343. *is64 = is64l;
  344. }
  345. off = EI_NIDENT;
  346. while (hdr != e_ident_local && off < hdr_size) {
  347. size_t br = read(fd, hdr + off, hdr_size - off);
  348. switch (br) {
  349. case 0:
  350. error_setg(errp, "File too short: %s", filename);
  351. goto fail;
  352. case -1:
  353. error_setg_errno(errp, errno, "Failed to read file: %s",
  354. filename);
  355. goto fail;
  356. }
  357. off += br;
  358. }
  359. fail:
  360. close(fd);
  361. }
  362. /* return < 0 if error, otherwise the number of bytes loaded in memory */
  363. ssize_t load_elf(const char *filename,
  364. uint64_t (*elf_note_fn)(void *, void *, bool),
  365. uint64_t (*translate_fn)(void *, uint64_t),
  366. void *translate_opaque, uint64_t *pentry, uint64_t *lowaddr,
  367. uint64_t *highaddr, uint32_t *pflags, int elf_data_order,
  368. int elf_machine, int clear_lsb, int data_swab)
  369. {
  370. return load_elf_as(filename, elf_note_fn, translate_fn, translate_opaque,
  371. pentry, lowaddr, highaddr, pflags, elf_data_order,
  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. if (!cpr_is_incoming()) {
  898. memcpy(data, rom->data, rom->datasize);
  899. }
  900. return data;
  901. }
  902. ssize_t rom_add_file(const char *file, const char *fw_dir,
  903. hwaddr addr, int32_t bootindex,
  904. bool has_option_rom, MemoryRegion *mr,
  905. AddressSpace *as)
  906. {
  907. MachineClass *mc = MACHINE_GET_CLASS(qdev_get_machine());
  908. Rom *rom;
  909. gsize size;
  910. g_autoptr(GError) gerr = NULL;
  911. char devpath[100];
  912. if (as && mr) {
  913. fprintf(stderr, "Specifying an Address Space and Memory Region is " \
  914. "not valid when loading a rom\n");
  915. /* We haven't allocated anything so we don't need any cleanup */
  916. return -1;
  917. }
  918. rom = g_malloc0(sizeof(*rom));
  919. rom->name = g_strdup(file);
  920. rom->path = qemu_find_file(QEMU_FILE_TYPE_BIOS, rom->name);
  921. rom->as = as;
  922. if (rom->path == NULL) {
  923. rom->path = g_strdup(file);
  924. }
  925. if (!g_file_get_contents(rom->path, (gchar **) &rom->data,
  926. &size, &gerr)) {
  927. fprintf(stderr, "rom: file %-20s: error %s\n",
  928. rom->name, gerr->message);
  929. goto err;
  930. }
  931. if (fw_dir) {
  932. rom->fw_dir = g_strdup(fw_dir);
  933. rom->fw_file = g_strdup(file);
  934. }
  935. rom->addr = addr;
  936. rom->romsize = size;
  937. rom->datasize = rom->romsize;
  938. rom_insert(rom);
  939. if (rom->fw_file && fw_cfg) {
  940. const char *basename;
  941. char fw_file_name[FW_CFG_MAX_FILE_PATH];
  942. void *data;
  943. basename = strrchr(rom->fw_file, '/');
  944. if (basename) {
  945. basename++;
  946. } else {
  947. basename = rom->fw_file;
  948. }
  949. snprintf(fw_file_name, sizeof(fw_file_name), "%s/%s", rom->fw_dir,
  950. basename);
  951. snprintf(devpath, sizeof(devpath), "/rom@%s", fw_file_name);
  952. if ((!has_option_rom || mc->option_rom_has_mr) && mc->rom_file_has_mr) {
  953. data = rom_set_mr(rom, OBJECT(fw_cfg), devpath, true);
  954. } else {
  955. data = rom->data;
  956. }
  957. fw_cfg_add_file(fw_cfg, fw_file_name, data, rom->romsize);
  958. } else {
  959. if (mr) {
  960. rom->mr = mr;
  961. snprintf(devpath, sizeof(devpath), "/rom@%s", file);
  962. } else {
  963. snprintf(devpath, sizeof(devpath), "/rom@" HWADDR_FMT_plx, addr);
  964. }
  965. }
  966. add_boot_device_path(bootindex, NULL, devpath);
  967. return 0;
  968. err:
  969. rom_free(rom);
  970. return -1;
  971. }
  972. MemoryRegion *rom_add_blob(const char *name, const void *blob, size_t len,
  973. size_t max_len, hwaddr addr, const char *fw_file_name,
  974. FWCfgCallback fw_callback, void *callback_opaque,
  975. AddressSpace *as, bool read_only)
  976. {
  977. MachineClass *mc = MACHINE_GET_CLASS(qdev_get_machine());
  978. Rom *rom;
  979. MemoryRegion *mr = NULL;
  980. rom = g_malloc0(sizeof(*rom));
  981. rom->name = g_strdup(name);
  982. rom->as = as;
  983. rom->addr = addr;
  984. rom->romsize = max_len ? max_len : len;
  985. rom->datasize = len;
  986. g_assert(rom->romsize >= rom->datasize);
  987. rom->data = g_malloc0(rom->datasize);
  988. memcpy(rom->data, blob, len);
  989. rom_insert(rom);
  990. if (fw_file_name && fw_cfg) {
  991. char devpath[100];
  992. void *data;
  993. if (read_only) {
  994. snprintf(devpath, sizeof(devpath), "/rom@%s", fw_file_name);
  995. } else {
  996. snprintf(devpath, sizeof(devpath), "/ram@%s", fw_file_name);
  997. }
  998. if (mc->rom_file_has_mr) {
  999. data = rom_set_mr(rom, OBJECT(fw_cfg), devpath, read_only);
  1000. mr = rom->mr;
  1001. } else {
  1002. data = rom->data;
  1003. }
  1004. fw_cfg_add_file_callback(fw_cfg, fw_file_name,
  1005. fw_callback, NULL, callback_opaque,
  1006. data, rom->datasize, read_only);
  1007. }
  1008. return mr;
  1009. }
  1010. /* This function is specific for elf program because we don't need to allocate
  1011. * all the rom. We just allocate the first part and the rest is just zeros. This
  1012. * is why romsize and datasize are different. Also, this function takes its own
  1013. * reference to "mapped_file", so we don't have to allocate and copy the buffer.
  1014. */
  1015. int rom_add_elf_program(const char *name, GMappedFile *mapped_file, void *data,
  1016. size_t datasize, size_t romsize, hwaddr addr,
  1017. AddressSpace *as)
  1018. {
  1019. Rom *rom;
  1020. rom = g_malloc0(sizeof(*rom));
  1021. rom->name = g_strdup(name);
  1022. rom->addr = addr;
  1023. rom->datasize = datasize;
  1024. rom->romsize = romsize;
  1025. rom->data = data;
  1026. rom->as = as;
  1027. if (mapped_file && data) {
  1028. g_mapped_file_ref(mapped_file);
  1029. rom->mapped_file = mapped_file;
  1030. }
  1031. rom_insert(rom);
  1032. return 0;
  1033. }
  1034. ssize_t rom_add_vga(const char *file)
  1035. {
  1036. return rom_add_file(file, "vgaroms", 0, -1, true, NULL, NULL);
  1037. }
  1038. ssize_t rom_add_option(const char *file, int32_t bootindex)
  1039. {
  1040. return rom_add_file(file, "genroms", 0, bootindex, true, NULL, NULL);
  1041. }
  1042. static void rom_reset(void *unused)
  1043. {
  1044. Rom *rom;
  1045. QTAILQ_FOREACH(rom, &roms, next) {
  1046. if (rom->fw_file) {
  1047. continue;
  1048. }
  1049. /*
  1050. * We don't need to fill in the RAM with ROM data because we'll fill
  1051. * the data in during the next incoming migration in all cases. Note
  1052. * that some of those RAMs can actually be modified by the guest.
  1053. */
  1054. if (runstate_check(RUN_STATE_INMIGRATE)) {
  1055. if (rom->data && rom->isrom) {
  1056. /*
  1057. * Free it so that a rom_reset after migration doesn't
  1058. * overwrite a potentially modified 'rom'.
  1059. */
  1060. rom_free_data(rom);
  1061. }
  1062. continue;
  1063. }
  1064. if (rom->data == NULL) {
  1065. continue;
  1066. }
  1067. if (rom->mr) {
  1068. void *host = memory_region_get_ram_ptr(rom->mr);
  1069. memcpy(host, rom->data, rom->datasize);
  1070. memset(host + rom->datasize, 0, rom->romsize - rom->datasize);
  1071. } else {
  1072. address_space_write_rom(rom->as, rom->addr, MEMTXATTRS_UNSPECIFIED,
  1073. rom->data, rom->datasize);
  1074. address_space_set(rom->as, rom->addr + rom->datasize, 0,
  1075. rom->romsize - rom->datasize,
  1076. MEMTXATTRS_UNSPECIFIED);
  1077. }
  1078. if (rom->isrom) {
  1079. /* rom needs to be written only once */
  1080. rom_free_data(rom);
  1081. }
  1082. /*
  1083. * The rom loader is really on the same level as firmware in the guest
  1084. * shadowing a ROM into RAM. Such a shadowing mechanism needs to ensure
  1085. * that the instruction cache for that new region is clear, so that the
  1086. * CPU definitely fetches its instructions from the just written data.
  1087. */
  1088. cpu_flush_icache_range(rom->addr, rom->datasize);
  1089. trace_loader_write_rom(rom->name, rom->addr, rom->datasize, rom->isrom);
  1090. }
  1091. }
  1092. /* Return true if two consecutive ROMs in the ROM list overlap */
  1093. static bool roms_overlap(Rom *last_rom, Rom *this_rom)
  1094. {
  1095. if (!last_rom) {
  1096. return false;
  1097. }
  1098. return last_rom->as == this_rom->as &&
  1099. last_rom->addr + last_rom->romsize > this_rom->addr;
  1100. }
  1101. static const char *rom_as_name(Rom *rom)
  1102. {
  1103. const char *name = rom->as ? rom->as->name : NULL;
  1104. return name ?: "anonymous";
  1105. }
  1106. static void rom_print_overlap_error_header(void)
  1107. {
  1108. error_report("Some ROM regions are overlapping");
  1109. error_printf(
  1110. "These ROM regions might have been loaded by "
  1111. "direct user request or by default.\n"
  1112. "They could be BIOS/firmware images, a guest kernel, "
  1113. "initrd or some other file loaded into guest memory.\n"
  1114. "Check whether you intended to load all this guest code, and "
  1115. "whether it has been built to load to the correct addresses.\n");
  1116. }
  1117. static void rom_print_one_overlap_error(Rom *last_rom, Rom *rom)
  1118. {
  1119. error_printf(
  1120. "\nThe following two regions overlap (in the %s address space):\n",
  1121. rom_as_name(rom));
  1122. error_printf(
  1123. " %s (addresses 0x" HWADDR_FMT_plx " - 0x" HWADDR_FMT_plx ")\n",
  1124. last_rom->name, last_rom->addr, last_rom->addr + last_rom->romsize);
  1125. error_printf(
  1126. " %s (addresses 0x" HWADDR_FMT_plx " - 0x" HWADDR_FMT_plx ")\n",
  1127. rom->name, rom->addr, rom->addr + rom->romsize);
  1128. }
  1129. int rom_check_and_register_reset(void)
  1130. {
  1131. MemoryRegionSection section;
  1132. Rom *rom, *last_rom = NULL;
  1133. bool found_overlap = false;
  1134. QTAILQ_FOREACH(rom, &roms, next) {
  1135. if (rom->fw_file) {
  1136. continue;
  1137. }
  1138. if (!rom->mr) {
  1139. if (roms_overlap(last_rom, rom)) {
  1140. if (!found_overlap) {
  1141. found_overlap = true;
  1142. rom_print_overlap_error_header();
  1143. }
  1144. rom_print_one_overlap_error(last_rom, rom);
  1145. /* Keep going through the list so we report all overlaps */
  1146. }
  1147. last_rom = rom;
  1148. }
  1149. section = memory_region_find(rom->mr ? rom->mr : get_system_memory(),
  1150. rom->addr, 1);
  1151. rom->isrom = int128_nz(section.size) && memory_region_is_rom(section.mr);
  1152. memory_region_unref(section.mr);
  1153. }
  1154. if (found_overlap) {
  1155. return -1;
  1156. }
  1157. qemu_register_reset(rom_reset, NULL);
  1158. roms_loaded = 1;
  1159. return 0;
  1160. }
  1161. void rom_set_fw(FWCfgState *f)
  1162. {
  1163. fw_cfg = f;
  1164. }
  1165. void rom_set_order_override(int order)
  1166. {
  1167. if (!fw_cfg)
  1168. return;
  1169. fw_cfg_set_order_override(fw_cfg, order);
  1170. }
  1171. void rom_reset_order_override(void)
  1172. {
  1173. if (!fw_cfg)
  1174. return;
  1175. fw_cfg_reset_order_override(fw_cfg);
  1176. }
  1177. void rom_transaction_begin(void)
  1178. {
  1179. Rom *rom;
  1180. /* Ignore ROMs added without the transaction API */
  1181. QTAILQ_FOREACH(rom, &roms, next) {
  1182. rom->committed = true;
  1183. }
  1184. }
  1185. void rom_transaction_end(bool commit)
  1186. {
  1187. Rom *rom;
  1188. Rom *tmp;
  1189. QTAILQ_FOREACH_SAFE(rom, &roms, next, tmp) {
  1190. if (rom->committed) {
  1191. continue;
  1192. }
  1193. if (commit) {
  1194. rom->committed = true;
  1195. } else {
  1196. QTAILQ_REMOVE(&roms, rom, next);
  1197. rom_free(rom);
  1198. }
  1199. }
  1200. }
  1201. static Rom *find_rom(hwaddr addr, size_t size)
  1202. {
  1203. Rom *rom;
  1204. QTAILQ_FOREACH(rom, &roms, next) {
  1205. if (rom->fw_file) {
  1206. continue;
  1207. }
  1208. if (rom->mr) {
  1209. continue;
  1210. }
  1211. if (rom->addr > addr) {
  1212. continue;
  1213. }
  1214. if (rom->addr + rom->romsize < addr + size) {
  1215. continue;
  1216. }
  1217. return rom;
  1218. }
  1219. return NULL;
  1220. }
  1221. typedef struct RomSec {
  1222. hwaddr base;
  1223. int se; /* start/end flag */
  1224. } RomSec;
  1225. /*
  1226. * Sort into address order. We break ties between rom-startpoints
  1227. * and rom-endpoints in favour of the startpoint, by sorting the 0->1
  1228. * transition before the 1->0 transition. Either way round would
  1229. * work, but this way saves a little work later by avoiding
  1230. * dealing with "gaps" of 0 length.
  1231. */
  1232. static gint sort_secs(gconstpointer a, gconstpointer b)
  1233. {
  1234. RomSec *ra = (RomSec *) a;
  1235. RomSec *rb = (RomSec *) b;
  1236. if (ra->base == rb->base) {
  1237. return ra->se - rb->se;
  1238. }
  1239. return ra->base > rb->base ? 1 : -1;
  1240. }
  1241. static GList *add_romsec_to_list(GList *secs, hwaddr base, int se)
  1242. {
  1243. RomSec *cand = g_new(RomSec, 1);
  1244. cand->base = base;
  1245. cand->se = se;
  1246. return g_list_prepend(secs, cand);
  1247. }
  1248. RomGap rom_find_largest_gap_between(hwaddr base, size_t size)
  1249. {
  1250. Rom *rom;
  1251. RomSec *cand;
  1252. RomGap res = {0, 0};
  1253. hwaddr gapstart = base;
  1254. GList *it, *secs = NULL;
  1255. int count = 0;
  1256. QTAILQ_FOREACH(rom, &roms, next) {
  1257. /* Ignore blobs being loaded to special places */
  1258. if (rom->mr || rom->fw_file) {
  1259. continue;
  1260. }
  1261. /* ignore anything finishing below base */
  1262. if (rom->addr + rom->romsize <= base) {
  1263. continue;
  1264. }
  1265. /* ignore anything starting above the region */
  1266. if (rom->addr >= base + size) {
  1267. continue;
  1268. }
  1269. /* Save the start and end of each relevant ROM */
  1270. secs = add_romsec_to_list(secs, rom->addr, 1);
  1271. if (rom->addr + rom->romsize < base + size) {
  1272. secs = add_romsec_to_list(secs, rom->addr + rom->romsize, -1);
  1273. }
  1274. }
  1275. /* sentinel */
  1276. secs = add_romsec_to_list(secs, base + size, 1);
  1277. secs = g_list_sort(secs, sort_secs);
  1278. for (it = g_list_first(secs); it; it = g_list_next(it)) {
  1279. cand = (RomSec *) it->data;
  1280. if (count == 0 && count + cand->se == 1) {
  1281. size_t gap = cand->base - gapstart;
  1282. if (gap > res.size) {
  1283. res.base = gapstart;
  1284. res.size = gap;
  1285. }
  1286. } else if (count == 1 && count + cand->se == 0) {
  1287. gapstart = cand->base;
  1288. }
  1289. count += cand->se;
  1290. }
  1291. g_list_free_full(secs, g_free);
  1292. return res;
  1293. }
  1294. /*
  1295. * Copies memory from registered ROMs to dest. Any memory that is contained in
  1296. * a ROM between addr and addr + size is copied. Note that this can involve
  1297. * multiple ROMs, which need not start at addr and need not end at addr + size.
  1298. */
  1299. int rom_copy(uint8_t *dest, hwaddr addr, size_t size)
  1300. {
  1301. hwaddr end = addr + size;
  1302. uint8_t *s, *d = dest;
  1303. size_t l = 0;
  1304. Rom *rom;
  1305. QTAILQ_FOREACH(rom, &roms, next) {
  1306. if (rom->fw_file) {
  1307. continue;
  1308. }
  1309. if (rom->mr) {
  1310. continue;
  1311. }
  1312. if (rom->addr + rom->romsize < addr) {
  1313. continue;
  1314. }
  1315. if (rom->addr > end || rom->addr < addr) {
  1316. break;
  1317. }
  1318. d = dest + (rom->addr - addr);
  1319. s = rom->data;
  1320. l = rom->datasize;
  1321. if ((d + l) > (dest + size)) {
  1322. l = dest - d;
  1323. }
  1324. if (l > 0) {
  1325. memcpy(d, s, l);
  1326. }
  1327. if (rom->romsize > rom->datasize) {
  1328. /* If datasize is less than romsize, it means that we didn't
  1329. * allocate all the ROM because the trailing data are only zeros.
  1330. */
  1331. d += l;
  1332. l = rom->romsize - rom->datasize;
  1333. if ((d + l) > (dest + size)) {
  1334. /* Rom size doesn't fit in the destination area. Adjust to avoid
  1335. * overflow.
  1336. */
  1337. l = dest - d;
  1338. }
  1339. if (l > 0) {
  1340. memset(d, 0x0, l);
  1341. }
  1342. }
  1343. }
  1344. return (d + l) - dest;
  1345. }
  1346. void *rom_ptr(hwaddr addr, size_t size)
  1347. {
  1348. Rom *rom;
  1349. rom = find_rom(addr, size);
  1350. if (!rom || !rom->data)
  1351. return NULL;
  1352. return rom->data + (addr - rom->addr);
  1353. }
  1354. typedef struct FindRomCBData {
  1355. size_t size; /* Amount of data we want from ROM, in bytes */
  1356. MemoryRegion *mr; /* MR at the unaliased guest addr */
  1357. hwaddr xlat; /* Offset of addr within mr */
  1358. void *rom; /* Output: rom data pointer, if found */
  1359. } FindRomCBData;
  1360. static bool find_rom_cb(Int128 start, Int128 len, const MemoryRegion *mr,
  1361. hwaddr offset_in_region, void *opaque)
  1362. {
  1363. FindRomCBData *cbdata = opaque;
  1364. hwaddr alias_addr;
  1365. if (mr != cbdata->mr) {
  1366. return false;
  1367. }
  1368. alias_addr = int128_get64(start) + cbdata->xlat - offset_in_region;
  1369. cbdata->rom = rom_ptr(alias_addr, cbdata->size);
  1370. if (!cbdata->rom) {
  1371. return false;
  1372. }
  1373. /* Found a match, stop iterating */
  1374. return true;
  1375. }
  1376. void *rom_ptr_for_as(AddressSpace *as, hwaddr addr, size_t size)
  1377. {
  1378. /*
  1379. * Find any ROM data for the given guest address range. If there
  1380. * is a ROM blob then return a pointer to the host memory
  1381. * corresponding to 'addr'; otherwise return NULL.
  1382. *
  1383. * We look not only for ROM blobs that were loaded directly to
  1384. * addr, but also for ROM blobs that were loaded to aliases of
  1385. * that memory at other addresses within the AddressSpace.
  1386. *
  1387. * Note that we do not check @as against the 'as' member in the
  1388. * 'struct Rom' returned by rom_ptr(). The Rom::as is the
  1389. * AddressSpace which the rom blob should be written to, whereas
  1390. * our @as argument is the AddressSpace which we are (effectively)
  1391. * reading from, and the same underlying RAM will often be visible
  1392. * in multiple AddressSpaces. (A common example is a ROM blob
  1393. * written to the 'system' address space but then read back via a
  1394. * CPU's cpu->as pointer.) This does mean we might potentially
  1395. * return a false-positive match if a ROM blob was loaded into an
  1396. * AS which is entirely separate and distinct from the one we're
  1397. * querying, but this issue exists also for rom_ptr() and hasn't
  1398. * caused any problems in practice.
  1399. */
  1400. FlatView *fv;
  1401. void *rom;
  1402. hwaddr len_unused;
  1403. FindRomCBData cbdata = {};
  1404. /* Easy case: there's data at the actual address */
  1405. rom = rom_ptr(addr, size);
  1406. if (rom) {
  1407. return rom;
  1408. }
  1409. RCU_READ_LOCK_GUARD();
  1410. fv = address_space_to_flatview(as);
  1411. cbdata.mr = flatview_translate(fv, addr, &cbdata.xlat, &len_unused,
  1412. false, MEMTXATTRS_UNSPECIFIED);
  1413. if (!cbdata.mr) {
  1414. /* Nothing at this address, so there can't be any aliasing */
  1415. return NULL;
  1416. }
  1417. cbdata.size = size;
  1418. flatview_for_each_range(fv, find_rom_cb, &cbdata);
  1419. return cbdata.rom;
  1420. }
  1421. HumanReadableText *qmp_x_query_roms(Error **errp)
  1422. {
  1423. Rom *rom;
  1424. g_autoptr(GString) buf = g_string_new("");
  1425. QTAILQ_FOREACH(rom, &roms, next) {
  1426. if (rom->mr) {
  1427. g_string_append_printf(buf, "%s"
  1428. " size=0x%06zx name=\"%s\"\n",
  1429. memory_region_name(rom->mr),
  1430. rom->romsize,
  1431. rom->name);
  1432. } else if (!rom->fw_file) {
  1433. g_string_append_printf(buf, "addr=" HWADDR_FMT_plx
  1434. " size=0x%06zx mem=%s name=\"%s\"\n",
  1435. rom->addr, rom->romsize,
  1436. rom->isrom ? "rom" : "ram",
  1437. rom->name);
  1438. } else {
  1439. g_string_append_printf(buf, "fw=%s/%s"
  1440. " size=0x%06zx name=\"%s\"\n",
  1441. rom->fw_dir,
  1442. rom->fw_file,
  1443. rom->romsize,
  1444. rom->name);
  1445. }
  1446. }
  1447. return human_readable_text_from_str(buf);
  1448. }
  1449. typedef enum HexRecord HexRecord;
  1450. enum HexRecord {
  1451. DATA_RECORD = 0,
  1452. EOF_RECORD,
  1453. EXT_SEG_ADDR_RECORD,
  1454. START_SEG_ADDR_RECORD,
  1455. EXT_LINEAR_ADDR_RECORD,
  1456. START_LINEAR_ADDR_RECORD,
  1457. };
  1458. /* Each record contains a 16-bit address which is combined with the upper 16
  1459. * bits of the implicit "next address" to form a 32-bit address.
  1460. */
  1461. #define NEXT_ADDR_MASK 0xffff0000
  1462. #define DATA_FIELD_MAX_LEN 0xff
  1463. #define LEN_EXCEPT_DATA 0x5
  1464. /* 0x5 = sizeof(byte_count) + sizeof(address) + sizeof(record_type) +
  1465. * sizeof(checksum) */
  1466. typedef struct {
  1467. uint8_t byte_count;
  1468. uint16_t address;
  1469. uint8_t record_type;
  1470. uint8_t data[DATA_FIELD_MAX_LEN];
  1471. uint8_t checksum;
  1472. } HexLine;
  1473. /* return 0 or -1 if error */
  1474. static bool parse_record(HexLine *line, uint8_t *our_checksum, const uint8_t c,
  1475. uint32_t *index, const bool in_process)
  1476. {
  1477. /* +-------+---------------+-------+---------------------+--------+
  1478. * | byte | |record | | |
  1479. * | count | address | type | data |checksum|
  1480. * +-------+---------------+-------+---------------------+--------+
  1481. * ^ ^ ^ ^ ^ ^
  1482. * |1 byte | 2 bytes |1 byte | 0-255 bytes | 1 byte |
  1483. */
  1484. uint8_t value = 0;
  1485. uint32_t idx = *index;
  1486. /* ignore space */
  1487. if (g_ascii_isspace(c)) {
  1488. return true;
  1489. }
  1490. if (!g_ascii_isxdigit(c) || !in_process) {
  1491. return false;
  1492. }
  1493. value = g_ascii_xdigit_value(c);
  1494. value = (idx & 0x1) ? (value & 0xf) : (value << 4);
  1495. if (idx < 2) {
  1496. line->byte_count |= value;
  1497. } else if (2 <= idx && idx < 6) {
  1498. line->address <<= 4;
  1499. line->address += g_ascii_xdigit_value(c);
  1500. } else if (6 <= idx && idx < 8) {
  1501. line->record_type |= value;
  1502. } else if (8 <= idx && idx < 8 + 2 * line->byte_count) {
  1503. line->data[(idx - 8) >> 1] |= value;
  1504. } else if (8 + 2 * line->byte_count <= idx &&
  1505. idx < 10 + 2 * line->byte_count) {
  1506. line->checksum |= value;
  1507. } else {
  1508. return false;
  1509. }
  1510. *our_checksum += value;
  1511. ++(*index);
  1512. return true;
  1513. }
  1514. typedef struct {
  1515. const char *filename;
  1516. HexLine line;
  1517. uint8_t *bin_buf;
  1518. hwaddr *start_addr;
  1519. int total_size;
  1520. uint32_t next_address_to_write;
  1521. uint32_t current_address;
  1522. uint32_t current_rom_index;
  1523. uint32_t rom_start_address;
  1524. AddressSpace *as;
  1525. bool complete;
  1526. } HexParser;
  1527. /* return size or -1 if error */
  1528. static int handle_record_type(HexParser *parser)
  1529. {
  1530. HexLine *line = &(parser->line);
  1531. switch (line->record_type) {
  1532. case DATA_RECORD:
  1533. parser->current_address =
  1534. (parser->next_address_to_write & NEXT_ADDR_MASK) | line->address;
  1535. /* verify this is a contiguous block of memory */
  1536. if (parser->current_address != parser->next_address_to_write) {
  1537. if (parser->current_rom_index != 0) {
  1538. rom_add_blob_fixed_as(parser->filename, parser->bin_buf,
  1539. parser->current_rom_index,
  1540. parser->rom_start_address, parser->as);
  1541. }
  1542. parser->rom_start_address = parser->current_address;
  1543. parser->current_rom_index = 0;
  1544. }
  1545. /* copy from line buffer to output bin_buf */
  1546. memcpy(parser->bin_buf + parser->current_rom_index, line->data,
  1547. line->byte_count);
  1548. parser->current_rom_index += line->byte_count;
  1549. parser->total_size += line->byte_count;
  1550. /* save next address to write */
  1551. parser->next_address_to_write =
  1552. parser->current_address + line->byte_count;
  1553. break;
  1554. case EOF_RECORD:
  1555. if (parser->current_rom_index != 0) {
  1556. rom_add_blob_fixed_as(parser->filename, parser->bin_buf,
  1557. parser->current_rom_index,
  1558. parser->rom_start_address, parser->as);
  1559. }
  1560. parser->complete = true;
  1561. return parser->total_size;
  1562. case EXT_SEG_ADDR_RECORD:
  1563. case EXT_LINEAR_ADDR_RECORD:
  1564. if (line->byte_count != 2 && line->address != 0) {
  1565. return -1;
  1566. }
  1567. if (parser->current_rom_index != 0) {
  1568. rom_add_blob_fixed_as(parser->filename, parser->bin_buf,
  1569. parser->current_rom_index,
  1570. parser->rom_start_address, parser->as);
  1571. }
  1572. /* save next address to write,
  1573. * in case of non-contiguous block of memory */
  1574. parser->next_address_to_write = (line->data[0] << 12) |
  1575. (line->data[1] << 4);
  1576. if (line->record_type == EXT_LINEAR_ADDR_RECORD) {
  1577. parser->next_address_to_write <<= 12;
  1578. }
  1579. parser->rom_start_address = parser->next_address_to_write;
  1580. parser->current_rom_index = 0;
  1581. break;
  1582. case START_SEG_ADDR_RECORD:
  1583. if (line->byte_count != 4 && line->address != 0) {
  1584. return -1;
  1585. }
  1586. /* x86 16-bit CS:IP segmented addressing */
  1587. *(parser->start_addr) = (((line->data[0] << 8) | line->data[1]) << 4) +
  1588. ((line->data[2] << 8) | line->data[3]);
  1589. break;
  1590. case START_LINEAR_ADDR_RECORD:
  1591. if (line->byte_count != 4 && line->address != 0) {
  1592. return -1;
  1593. }
  1594. *(parser->start_addr) = ldl_be_p(line->data);
  1595. break;
  1596. default:
  1597. return -1;
  1598. }
  1599. return parser->total_size;
  1600. }
  1601. /* return size or -1 if error */
  1602. static int parse_hex_blob(const char *filename, hwaddr *addr, uint8_t *hex_blob,
  1603. size_t hex_blob_size, AddressSpace *as)
  1604. {
  1605. bool in_process = false; /* avoid re-enter and
  1606. * check whether record begin with ':' */
  1607. uint8_t *end = hex_blob + hex_blob_size;
  1608. uint8_t our_checksum = 0;
  1609. uint32_t record_index = 0;
  1610. HexParser parser = {
  1611. .filename = filename,
  1612. .bin_buf = g_malloc(hex_blob_size),
  1613. .start_addr = addr,
  1614. .as = as,
  1615. .complete = false
  1616. };
  1617. rom_transaction_begin();
  1618. for (; hex_blob < end && !parser.complete; ++hex_blob) {
  1619. switch (*hex_blob) {
  1620. case '\r':
  1621. case '\n':
  1622. if (!in_process) {
  1623. break;
  1624. }
  1625. in_process = false;
  1626. if ((LEN_EXCEPT_DATA + parser.line.byte_count) * 2 !=
  1627. record_index ||
  1628. our_checksum != 0) {
  1629. parser.total_size = -1;
  1630. goto out;
  1631. }
  1632. if (handle_record_type(&parser) == -1) {
  1633. parser.total_size = -1;
  1634. goto out;
  1635. }
  1636. break;
  1637. /* start of a new record. */
  1638. case ':':
  1639. memset(&parser.line, 0, sizeof(HexLine));
  1640. in_process = true;
  1641. record_index = 0;
  1642. break;
  1643. /* decoding lines */
  1644. default:
  1645. if (!parse_record(&parser.line, &our_checksum, *hex_blob,
  1646. &record_index, in_process)) {
  1647. parser.total_size = -1;
  1648. goto out;
  1649. }
  1650. break;
  1651. }
  1652. }
  1653. out:
  1654. g_free(parser.bin_buf);
  1655. rom_transaction_end(parser.total_size != -1);
  1656. return parser.total_size;
  1657. }
  1658. /* return size or -1 if error */
  1659. ssize_t load_targphys_hex_as(const char *filename, hwaddr *entry,
  1660. AddressSpace *as)
  1661. {
  1662. gsize hex_blob_size;
  1663. gchar *hex_blob;
  1664. ssize_t total_size = 0;
  1665. if (!g_file_get_contents(filename, &hex_blob, &hex_blob_size, NULL)) {
  1666. return -1;
  1667. }
  1668. total_size = parse_hex_blob(filename, entry, (uint8_t *)hex_blob,
  1669. hex_blob_size, as);
  1670. g_free(hex_blob);
  1671. return total_size;
  1672. }