all repos — mgba @ a75c019fab24f045069cb9a923d02795f4d6f564

mGBA Game Boy Advance Emulator

src/gba/serialize.c (view raw)

  1/* Copyright (c) 2013-2015 Jeffrey Pfau
  2 *
  3 * This Source Code Form is subject to the terms of the Mozilla Public
  4 * License, v. 2.0. If a copy of the MPL was not distributed with this
  5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  6#include "serialize.h"
  7
  8#include "core/sync.h"
  9#include "gba/audio.h"
 10#include "gba/cheats.h"
 11#include "gba/io.h"
 12#include "gba/rr/rr.h"
 13#include "gba/video.h"
 14
 15#include "util/memory.h"
 16#include "util/vfs.h"
 17
 18#include <fcntl.h>
 19#include <sys/time.h>
 20
 21#ifdef USE_PNG
 22#include "util/png-io.h"
 23#include <png.h>
 24#include <zlib.h>
 25#endif
 26
 27const uint32_t GBA_SAVESTATE_MAGIC = 0x01000000;
 28
 29struct GBABundledState {
 30	struct GBASerializedState* state;
 31	struct GBAExtdata* extdata;
 32};
 33
 34struct GBAExtdataHeader {
 35	uint32_t tag;
 36	int32_t size;
 37	int64_t offset;
 38};
 39
 40void GBASerialize(struct GBA* gba, struct GBASerializedState* state) {
 41	STORE_32(GBA_SAVESTATE_MAGIC, 0, &state->versionMagic);
 42	STORE_32(gba->biosChecksum, 0, &state->biosChecksum);
 43	STORE_32(gba->romCrc32, 0, &state->romCrc32);
 44
 45	if (gba->memory.rom) {
 46		state->id = ((struct GBACartridge*) gba->memory.rom)->id;
 47		memcpy(state->title, ((struct GBACartridge*) gba->memory.rom)->title, sizeof(state->title));
 48	} else {
 49		state->id = 0;
 50		memset(state->title, 0, sizeof(state->title));
 51	}
 52
 53	int i;
 54	for (i = 0; i < 16; ++i) {
 55		STORE_32(gba->cpu->gprs[i], i * sizeof(state->cpu.gprs[0]), state->cpu.gprs);
 56	}
 57	STORE_32(gba->cpu->cpsr.packed, 0, &state->cpu.cpsr.packed);
 58	STORE_32(gba->cpu->spsr.packed, 0, &state->cpu.spsr.packed);
 59	STORE_32(gba->cpu->cycles, 0, &state->cpu.cycles);
 60	STORE_32(gba->cpu->nextEvent, 0, &state->cpu.nextEvent);
 61	for (i = 0; i < 6; ++i) {
 62		int j;
 63		for (j = 0; j < 7; ++j) {
 64			STORE_32(gba->cpu->bankedRegisters[i][j], (i * 7 + j) * sizeof(gba->cpu->bankedRegisters[0][0]), state->cpu.bankedRegisters);
 65		}
 66		STORE_32(gba->cpu->bankedSPSRs[i], i * sizeof(gba->cpu->bankedSPSRs[0]), state->cpu.bankedSPSRs);
 67	}
 68
 69	state->biosPrefetch = gba->memory.biosPrefetch;
 70	STORE_32(gba->cpu->prefetch[0], 0, state->cpuPrefetch);
 71	STORE_32(gba->cpu->prefetch[1], 4, state->cpuPrefetch);
 72
 73	GBAMemorySerialize(&gba->memory, state);
 74	GBAIOSerialize(gba, state);
 75	GBAVideoSerialize(&gba->video, state);
 76	GBAAudioSerialize(&gba->audio, state);
 77	GBASavedataSerialize(&gba->memory.savedata, state);
 78
 79	struct timeval tv;
 80	if (!gettimeofday(&tv, 0)) {
 81		uint64_t usec = tv.tv_usec;
 82		usec += tv.tv_sec * 1000000LL;
 83		STORE_64(usec, 0, &state->creationUsec);
 84	} else {
 85		state->creationUsec = 0;
 86	}
 87	state->associatedStreamId = 0;
 88	if (gba->rr) {
 89		gba->rr->stateSaved(gba->rr, state);
 90	}
 91}
 92
 93bool GBADeserialize(struct GBA* gba, const struct GBASerializedState* state) {
 94	bool error = false;
 95	int32_t check;
 96	uint32_t ucheck;
 97	LOAD_32(ucheck, 0, &state->versionMagic);
 98	if (ucheck != GBA_SAVESTATE_MAGIC) {
 99		GBALog(gba, GBA_LOG_WARN, "Invalid or too new savestate: expected %08X, got %08X", GBA_SAVESTATE_MAGIC, ucheck);
100		error = true;
101	}
102	LOAD_32(ucheck, 0, &state->biosChecksum);
103	if (ucheck != gba->biosChecksum) {
104		GBALog(gba, GBA_LOG_WARN, "Savestate created using a different version of the BIOS: expected %08X, got %08X", gba->biosChecksum, ucheck);
105		uint32_t pc;
106		LOAD_32(pc, ARM_PC * sizeof(state->cpu.gprs[0]), state->cpu.gprs);
107		if (pc < SIZE_BIOS && pc >= 0x20) {
108			error = true;
109		}
110	}
111	if (gba->memory.rom && (state->id != ((struct GBACartridge*) gba->memory.rom)->id || memcmp(state->title, ((struct GBACartridge*) gba->memory.rom)->title, sizeof(state->title)))) {
112		GBALog(gba, GBA_LOG_WARN, "Savestate is for a different game");
113		error = true;
114	} else if (!gba->memory.rom && state->id != 0) {
115		GBALog(gba, GBA_LOG_WARN, "Savestate is for a game, but no game loaded");
116		error = true;
117	}
118	LOAD_32(ucheck, 0, &state->romCrc32);
119	if (ucheck != gba->romCrc32) {
120		GBALog(gba, GBA_LOG_WARN, "Savestate is for a different version of the game");
121	}
122	LOAD_32(check, 0, &state->cpu.cycles);
123	if (check < 0) {
124		GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: CPU cycles are negative");
125		error = true;
126	}
127	if (check >= (int32_t) GBA_ARM7TDMI_FREQUENCY) {
128		GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: CPU cycles are too high");
129		error = true;
130	}
131	LOAD_32(check, 0, &state->video.eventDiff);
132	if (check < 0) {
133		GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: video eventDiff is negative");
134		error = true;
135	}
136	LOAD_32(check, ARM_PC * sizeof(state->cpu.gprs[0]), state->cpu.gprs);
137	int region = (check >> BASE_OFFSET);
138	if ((region == REGION_CART0 || region == REGION_CART1 || region == REGION_CART2) && ((check - WORD_SIZE_ARM) & SIZE_CART0) >= gba->memory.romSize - WORD_SIZE_ARM) {
139		GBALog(gba, GBA_LOG_WARN, "Savestate created using a differently sized version of the ROM");
140		error = true;
141	}
142	if (error) {
143		return false;
144	}
145	size_t i;
146	for (i = 0; i < 16; ++i) {
147		LOAD_32(gba->cpu->gprs[i], i * sizeof(gba->cpu->gprs[0]), state->cpu.gprs);
148	}
149	LOAD_32(gba->cpu->cpsr.packed, 0, &state->cpu.cpsr.packed);
150	LOAD_32(gba->cpu->spsr.packed, 0, &state->cpu.spsr.packed);
151	LOAD_32(gba->cpu->cycles, 0, &state->cpu.cycles);
152	LOAD_32(gba->cpu->nextEvent, 0, &state->cpu.nextEvent);
153	for (i = 0; i < 6; ++i) {
154		int j;
155		for (j = 0; j < 7; ++j) {
156			LOAD_32(gba->cpu->bankedRegisters[i][j], (i * 7 + j) * sizeof(gba->cpu->bankedRegisters[0][0]), state->cpu.bankedRegisters);
157		}
158		LOAD_32(gba->cpu->bankedSPSRs[i], i * sizeof(gba->cpu->bankedSPSRs[0]), state->cpu.bankedSPSRs);
159	}
160	gba->cpu->privilegeMode = gba->cpu->cpsr.priv;
161	gba->cpu->memory.setActiveRegion(gba->cpu, gba->cpu->gprs[ARM_PC]);
162	if (state->biosPrefetch) {
163		LOAD_32(gba->memory.biosPrefetch, 0, &state->biosPrefetch);
164	}
165	if (gba->cpu->cpsr.t) {
166		gba->cpu->executionMode = MODE_THUMB;
167		if (state->cpuPrefetch[0] && state->cpuPrefetch[1]) {
168			LOAD_32(gba->cpu->prefetch[0], 0, state->cpuPrefetch);
169			LOAD_32(gba->cpu->prefetch[1], 4, state->cpuPrefetch);
170			gba->cpu->prefetch[0] &= 0xFFFF;
171			gba->cpu->prefetch[1] &= 0xFFFF;
172		} else {
173			// Maintain backwards compat
174			LOAD_16(gba->cpu->prefetch[0], (gba->cpu->gprs[ARM_PC] - WORD_SIZE_THUMB) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
175			LOAD_16(gba->cpu->prefetch[1], (gba->cpu->gprs[ARM_PC]) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
176		}
177	} else {
178		gba->cpu->executionMode = MODE_ARM;
179		if (state->cpuPrefetch[0] && state->cpuPrefetch[1]) {
180			LOAD_32(gba->cpu->prefetch[0], 0, state->cpuPrefetch);
181			LOAD_32(gba->cpu->prefetch[1], 4, state->cpuPrefetch);
182		} else {
183			// Maintain backwards compat
184			LOAD_32(gba->cpu->prefetch[0], (gba->cpu->gprs[ARM_PC] - WORD_SIZE_ARM) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
185			LOAD_32(gba->cpu->prefetch[1], (gba->cpu->gprs[ARM_PC]) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
186		}
187	}
188
189	GBAMemoryDeserialize(&gba->memory, state);
190	GBAIODeserialize(gba, state);
191	GBAVideoDeserialize(&gba->video, state);
192	GBAAudioDeserialize(&gba->audio, state);
193	GBASavedataDeserialize(&gba->memory.savedata, state);
194
195	if (gba->rr) {
196		gba->rr->stateLoaded(gba->rr, state);
197	}
198	return true;
199}
200
201struct VFile* GBAGetState(struct GBA* gba, struct VDir* dir, int slot, bool write) {
202	char basename[PATH_MAX];
203	separatePath(gba->activeFile, 0, basename, 0);
204	char path[PATH_MAX];
205	snprintf(path, sizeof(path), "%s.ss%i", basename, slot);
206	return dir->openFile(dir, path, write ? (O_CREAT | O_TRUNC | O_RDWR) : O_RDONLY);
207}
208
209void GBADeleteState(struct GBA* gba, struct VDir* dir, int slot) {
210	char basename[PATH_MAX];
211	separatePath(gba->activeFile, 0, basename, 0);
212	char path[PATH_MAX];
213	snprintf(path, sizeof(path), "%s.ss%i", basename, slot);
214	dir->deleteFile(dir, path);
215}
216
217#ifdef USE_PNG
218static bool _savePNGState(struct GBA* gba, struct VFile* vf, struct GBAExtdata* extdata) {
219	unsigned stride;
220	const void* pixels = 0;
221	gba->video.renderer->getPixels(gba->video.renderer, &stride, &pixels);
222	if (!pixels) {
223		return false;
224	}
225
226	struct GBASerializedState* state = GBAAllocateState();
227	if (!state) {
228		return false;
229	}
230	GBASerialize(gba, state);
231	uLongf len = compressBound(sizeof(*state));
232	void* buffer = malloc(len);
233	if (!buffer) {
234		GBADeallocateState(state);
235		return false;
236	}
237	compress(buffer, &len, (const Bytef*) state, sizeof(*state));
238	GBADeallocateState(state);
239
240	png_structp png = PNGWriteOpen(vf);
241	png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
242	if (!png || !info) {
243		PNGWriteClose(png, info);
244		free(buffer);
245		return false;
246	}
247	PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
248	PNGWriteCustomChunk(png, "gbAs", len, buffer);
249	if (extdata) {
250		uint32_t i;
251		for (i = 1; i < EXTDATA_MAX; ++i) {
252			if (!extdata->data[i].data) {
253				continue;
254			}
255			uLongf len = compressBound(extdata->data[i].size) + sizeof(uint32_t) * 2;
256			uint32_t* data = malloc(len);
257			if (!data) {
258				continue;
259			}
260			STORE_32(i, 0, data);
261			STORE_32(extdata->data[i].size, sizeof(uint32_t), data);
262			compress((Bytef*) (data + 2), &len, extdata->data[i].data, extdata->data[i].size);
263			PNGWriteCustomChunk(png, "gbAx", len + sizeof(uint32_t) * 2, data);
264			free(data);
265		}
266	}
267	PNGWriteClose(png, info);
268	free(buffer);
269	return true;
270}
271
272static int _loadPNGChunkHandler(png_structp png, png_unknown_chunkp chunk) {
273	struct GBABundledState* bundle = png_get_user_chunk_ptr(png);
274	if (!bundle) {
275		return 0;
276	}
277	if (!strcmp((const char*) chunk->name, "gbAs")) {
278		struct GBASerializedState* state = bundle->state;
279		if (!state) {
280			return 0;
281		}
282		uLongf len = sizeof(*state);
283		uncompress((Bytef*) state, &len, chunk->data, chunk->size);
284		return 1;
285	}
286	if (!strcmp((const char*) chunk->name, "gbAx")) {
287		struct GBAExtdata* extdata = bundle->extdata;
288		if (!extdata) {
289			return 0;
290		}
291		struct GBAExtdataItem item;
292		if (chunk->size < sizeof(uint32_t) * 2) {
293			return 0;
294		}
295		uint32_t tag;
296		LOAD_32(tag, 0, chunk->data);
297		LOAD_32(item.size, sizeof(uint32_t), chunk->data);
298		uLongf len = item.size;
299		if (item.size < 0 || tag == EXTDATA_NONE || tag >= EXTDATA_MAX) {
300			return 0;
301		}
302		item.data = malloc(item.size);
303		item.clean = free;
304		if (!item.data) {
305			return 0;
306		}
307		const uint8_t* data = chunk->data;
308		data += sizeof(uint32_t) * 2;
309		uncompress((Bytef*) item.data, &len, data, chunk->size);
310		item.size = len;
311		GBAExtdataPut(extdata, tag, &item);
312		return 1;
313	}
314	return 0;
315}
316
317static struct GBASerializedState* _loadPNGState(struct VFile* vf, struct GBAExtdata* extdata) {
318	png_structp png = PNGReadOpen(vf, PNG_HEADER_BYTES);
319	png_infop info = png_create_info_struct(png);
320	png_infop end = png_create_info_struct(png);
321	if (!png || !info || !end) {
322		PNGReadClose(png, info, end);
323		return false;
324	}
325	uint32_t* pixels = malloc(VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * 4);
326	if (!pixels) {
327		PNGReadClose(png, info, end);
328		return false;
329	}
330
331	struct GBASerializedState* state = GBAAllocateState();
332	struct GBABundledState bundle = {
333		.state = state,
334		.extdata = extdata
335	};
336
337	PNGInstallChunkHandler(png, &bundle, _loadPNGChunkHandler, "gbAs gbAx");
338	bool success = PNGReadHeader(png, info);
339	success = success && PNGReadPixels(png, info, pixels, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, VIDEO_HORIZONTAL_PIXELS);
340	success = success && PNGReadFooter(png, end);
341	PNGReadClose(png, info, end);
342
343	if (success) {
344		struct GBAExtdataItem item = {
345			.size = VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * 4,
346			.data = pixels,
347			.clean = free
348		};
349		GBAExtdataPut(extdata, EXTDATA_SCREENSHOT, &item);
350	} else {
351		free(pixels);
352		GBADeallocateState(state);
353		return 0;
354	}
355	return state;
356}
357#endif
358
359bool GBASaveStateNamed(struct GBA* gba, struct VFile* vf, int flags) {
360	struct GBAExtdata extdata;
361	GBAExtdataInit(&extdata);
362	if (flags & SAVESTATE_SAVEDATA) {
363		// TODO: A better way to do this would be nice
364		void* sram = malloc(SIZE_CART_FLASH1M);
365		struct VFile* svf = VFileFromMemory(sram, SIZE_CART_FLASH1M);
366		if (GBASavedataClone(&gba->memory.savedata, svf)) {
367			struct GBAExtdataItem item = {
368				.size = svf->seek(svf, 0, SEEK_CUR),
369				.data = sram,
370				.clean = free
371			};
372			GBAExtdataPut(&extdata, EXTDATA_SAVEDATA, &item);
373		} else {
374			free(sram);
375		}
376		svf->close(svf);
377	}
378	struct VFile* cheatVf = 0;
379	if (flags & SAVESTATE_CHEATS && gba->cpu->components && gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE]) {
380		struct GBACheatDevice* device = (struct GBACheatDevice*) gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE];
381		cheatVf = VFileMemChunk(0, 0);
382		if (cheatVf) {
383			GBACheatSaveFile(device, cheatVf);
384			struct GBAExtdataItem item = {
385				.size = cheatVf->size(cheatVf),
386				.data = cheatVf->map(cheatVf, cheatVf->size(cheatVf), MAP_READ),
387				.clean = 0
388			};
389			GBAExtdataPut(&extdata, EXTDATA_CHEATS, &item);
390		}
391	};
392#ifdef USE_PNG
393	if (!(flags & SAVESTATE_SCREENSHOT)) {
394#else
395	UNUSED(flags);
396#endif
397		vf->truncate(vf, sizeof(struct GBASerializedState));
398		struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_WRITE);
399		if (!state) {
400			GBAExtdataDeinit(&extdata);
401			if (cheatVf) {
402				cheatVf->close(cheatVf);
403			}
404			return false;
405		}
406		GBASerialize(gba, state);
407		vf->unmap(vf, state, sizeof(struct GBASerializedState));
408		vf->seek(vf, sizeof(struct GBASerializedState), SEEK_SET);
409		GBAExtdataSerialize(&extdata, vf);
410		GBAExtdataDeinit(&extdata);
411		if (cheatVf) {
412			cheatVf->close(cheatVf);
413		}
414		return true;
415#ifdef USE_PNG
416	}
417	else {
418		bool success = _savePNGState(gba, vf, &extdata);
419		GBAExtdataDeinit(&extdata);
420		return success;
421	}
422#endif
423	GBAExtdataDeinit(&extdata);
424	return false;
425}
426
427struct GBASerializedState* GBAExtractState(struct VFile* vf, struct GBAExtdata* extdata) {
428#ifdef USE_PNG
429	if (isPNG(vf)) {
430		return _loadPNGState(vf, extdata);
431	}
432#endif
433	vf->seek(vf, 0, SEEK_SET);
434	if (vf->size(vf) < (ssize_t) sizeof(struct GBASerializedState)) {
435		return false;
436	}
437	struct GBASerializedState* state = GBAAllocateState();
438	if (vf->read(vf, state, sizeof(*state)) != sizeof(*state)) {
439		GBADeallocateState(state);
440		return 0;
441	}
442	if (extdata) {
443		GBAExtdataDeserialize(extdata, vf);
444	}
445	return state;
446}
447
448bool GBALoadStateNamed(struct GBA* gba, struct VFile* vf, int flags) {
449	struct GBAExtdata extdata;
450	GBAExtdataInit(&extdata);
451	struct GBASerializedState* state = GBAExtractState(vf, &extdata);
452	if (!state) {
453		return false;
454	}
455	bool success = GBADeserialize(gba, state);
456	GBADeallocateState(state);
457
458	struct GBAExtdataItem item;
459	if (flags & SAVESTATE_SCREENSHOT && GBAExtdataGet(&extdata, EXTDATA_SCREENSHOT, &item)) {
460		if (item.size >= VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * 4) {
461			gba->video.renderer->putPixels(gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, item.data);
462			mCoreSyncForceFrame(gba->sync);
463		} else {
464			GBALog(gba, GBA_LOG_WARN, "Savestate includes invalid screenshot");
465		}
466	}
467	if (flags & SAVESTATE_SAVEDATA && GBAExtdataGet(&extdata, EXTDATA_SAVEDATA, &item)) {
468		struct VFile* svf = VFileFromMemory(item.data, item.size);
469		if (svf) {
470			GBASavedataLoad(&gba->memory.savedata, svf);
471			svf->close(svf);
472		}
473	}
474	if (flags & SAVESTATE_CHEATS && gba->cpu->components && gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE] && GBAExtdataGet(&extdata, EXTDATA_CHEATS, &item)) {
475		if (item.size) {
476			struct GBACheatDevice* device = (struct GBACheatDevice*) gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE];
477			struct VFile* svf = VFileFromMemory(item.data, item.size);
478			if (svf) {
479				GBACheatDeviceClear(device);
480				GBACheatParseFile(device, svf);
481				svf->close(svf);
482			}
483		}
484	}
485	GBAExtdataDeinit(&extdata);
486	return success;
487}
488
489bool GBAExtdataInit(struct GBAExtdata* extdata) {
490	memset(extdata->data, 0, sizeof(extdata->data));
491	return true;
492}
493
494void GBAExtdataDeinit(struct GBAExtdata* extdata) {
495	size_t i;
496	for (i = 1; i < EXTDATA_MAX; ++i) {
497		if (extdata->data[i].data && extdata->data[i].clean) {
498			extdata->data[i].clean(extdata->data[i].data);
499		}
500	}
501}
502
503void GBAExtdataPut(struct GBAExtdata* extdata, enum GBAExtdataTag tag, struct GBAExtdataItem* item) {
504	if (tag == EXTDATA_NONE || tag >= EXTDATA_MAX) {
505		return;
506	}
507
508	if (extdata->data[tag].data && extdata->data[tag].clean) {
509		extdata->data[tag].clean(extdata->data[tag].data);
510	}
511	extdata->data[tag] = *item;
512}
513
514bool GBAExtdataGet(struct GBAExtdata* extdata, enum GBAExtdataTag tag, struct GBAExtdataItem* item) {
515	if (tag == EXTDATA_NONE || tag >= EXTDATA_MAX) {
516		return false;
517	}
518
519	*item = extdata->data[tag];
520	return true;
521}
522
523bool GBAExtdataSerialize(struct GBAExtdata* extdata, struct VFile* vf) {
524	ssize_t position = vf->seek(vf, 0, SEEK_CUR);
525	ssize_t size = 2;
526	size_t i = 0;
527	for (i = 1; i < EXTDATA_MAX; ++i) {
528		if (extdata->data[i].data) {
529			size += sizeof(uint64_t) * 2;
530		}
531	}
532	if (size == 2) {
533		return true;
534	}
535	struct GBAExtdataHeader* header = malloc(size);
536	position += size;
537
538	size_t j;
539	for (i = 1, j = 0; i < EXTDATA_MAX; ++i) {
540		if (extdata->data[i].data) {
541			STORE_32(i, offsetof(struct GBAExtdataHeader, tag), &header[j]);
542			STORE_32(extdata->data[i].size, offsetof(struct GBAExtdataHeader, size), &header[j]);
543			STORE_64(position, offsetof(struct GBAExtdataHeader, offset), &header[j]);
544			position += extdata->data[i].size;
545			++j;
546		}
547	}
548	header[j].tag = 0;
549	header[j].size = 0;
550	header[j].offset = 0;
551
552	if (vf->write(vf, header, size) != size) {
553		free(header);
554		return false;
555	}
556	free(header);
557
558	for (i = 1; i < EXTDATA_MAX; ++i) {
559		if (extdata->data[i].data) {
560			if (vf->write(vf, extdata->data[i].data, extdata->data[i].size) != extdata->data[i].size) {
561				return false;
562			}
563		}
564	}
565	return true;
566}
567
568bool GBAExtdataDeserialize(struct GBAExtdata* extdata, struct VFile* vf) {
569	while (true) {
570		struct GBAExtdataHeader buffer, header;
571		if (vf->read(vf, &buffer, sizeof(buffer)) != sizeof(buffer)) {
572			return false;
573		}
574		LOAD_32(header.tag, 0, &buffer.tag);
575		LOAD_32(header.size, 0, &buffer.size);
576		LOAD_64(header.offset, 0, &buffer.offset);
577
578		if (header.tag == EXTDATA_NONE) {
579			break;
580		}
581		if (header.tag >= EXTDATA_MAX) {
582			continue;
583		}
584		ssize_t position = vf->seek(vf, 0, SEEK_CUR);
585		if (vf->seek(vf, header.offset, SEEK_SET) < 0) {
586			return false;
587		}
588		struct GBAExtdataItem item = {
589			.data = malloc(header.size),
590			.size = header.size,
591			.clean = free
592		};
593		if (!item.data) {
594			continue;
595		}
596		if (vf->read(vf, item.data, header.size) != header.size) {
597			free(item.data);
598			continue;
599		}
600		GBAExtdataPut(extdata, header.tag, &item);
601		vf->seek(vf, position, SEEK_SET);
602	};
603	return true;
604}
605
606struct GBASerializedState* GBAAllocateState(void) {
607	return anonymousMemoryMap(sizeof(struct GBASerializedState));
608}
609
610void GBADeallocateState(struct GBASerializedState* state) {
611	mappedMemoryFree(state, sizeof(struct GBASerializedState));
612}
613
614// TODO: Put back rewind
615
616void GBATakeScreenshot(struct GBA* gba, struct VDir* dir) {
617#ifdef USE_PNG
618	unsigned stride;
619	const void* pixels = 0;
620	char basename[PATH_MAX];
621	separatePath(gba->activeFile, 0, basename, 0);
622	struct VFile* vf = VDirFindNextAvailable(dir, basename, "-", ".png", O_CREAT | O_TRUNC | O_WRONLY);
623	bool success = false;
624	if (vf) {
625		gba->video.renderer->getPixels(gba->video.renderer, &stride, &pixels);
626		png_structp png = PNGWriteOpen(vf);
627		png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
628		success = PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
629		PNGWriteClose(png, info);
630		vf->close(vf);
631	}
632	if (success) {
633		GBALog(gba, GBA_LOG_STATUS, "Screenshot saved");
634		return;
635	}
636#else
637	UNUSED(dir);
638#endif
639	GBALog(gba, GBA_LOG_STATUS, "Failed to take screenshot");
640}