1 /* Copyright (c) 2013-2016 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 <mgba/core/core.h>
7 
8 #include <mgba/core/cheats.h>
9 #include <mgba/core/log.h>
10 #include <mgba/core/serialize.h>
11 #include <mgba-util/vfs.h>
12 #include <mgba/internal/debugger/symbols.h>
13 
14 #ifdef USE_ELF
15 #include <mgba-util/elf-read.h>
16 #endif
17 
18 #ifdef M_CORE_GB
19 #include <mgba/gb/core.h>
20 #include <mgba/gb/interface.h>
21 #endif
22 #ifdef M_CORE_GBA
23 #include <mgba/gba/core.h>
24 #include <mgba/gba/interface.h>
25 #endif
26 #ifndef MINIMAL_CORE
27 #include <mgba/feature/video-logger.h>
28 #endif
29 
30 static const struct mCoreFilter {
31 	bool (*filter)(struct VFile*);
32 	struct mCore* (*open)(void);
33 	enum mPlatform platform;
34 } _filters[] = {
35 #ifdef M_CORE_GBA
36 	{ GBAIsROM, GBACoreCreate, PLATFORM_GBA },
37 #endif
38 #ifdef M_CORE_GB
39 	{ GBIsROM, GBCoreCreate, PLATFORM_GB },
40 #endif
41 	{ 0, 0, PLATFORM_NONE }
42 };
43 
mCoreFindVF(struct VFile * vf)44 struct mCore* mCoreFindVF(struct VFile* vf) {
45 	if (!vf) {
46 		return NULL;
47 	}
48 	const struct mCoreFilter* filter;
49 	for (filter = &_filters[0]; filter->filter; ++filter) {
50 		if (filter->filter(vf)) {
51 			break;
52 		}
53 	}
54 	if (filter->open) {
55 		return filter->open();
56 	}
57 #ifndef MINIMAL_CORE
58 	return mVideoLogCoreFind(vf);
59 #endif
60 	return NULL;
61 }
62 
mCoreIsCompatible(struct VFile * vf)63 enum mPlatform mCoreIsCompatible(struct VFile* vf) {
64 	if (!vf) {
65 		return PLATFORM_NONE;
66 	}
67 	const struct mCoreFilter* filter;
68 	for (filter = &_filters[0]; filter->filter; ++filter) {
69 		if (filter->filter(vf)) {
70 			return filter->platform;
71 		}
72 	}
73 	return PLATFORM_NONE;
74 }
75 
76 #if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
77 #include <mgba-util/png-io.h>
78 
79 #ifdef PSP2
80 #include <psp2/photoexport.h>
81 #endif
82 
mCoreFind(const char * path)83 struct mCore* mCoreFind(const char* path) {
84 	struct VDir* archive = VDirOpenArchive(path);
85 	struct mCore* core = NULL;
86 	if (archive) {
87 		struct VDirEntry* dirent = archive->listNext(archive);
88 		while (dirent) {
89 			struct VFile* vf = archive->openFile(archive, dirent->name(dirent), O_RDONLY);
90 			if (!vf) {
91 				dirent = archive->listNext(archive);
92 				continue;
93 			}
94 			core = mCoreFindVF(vf);
95 			vf->close(vf);
96 			if (core) {
97 				break;
98 			}
99 			dirent = archive->listNext(archive);
100 		}
101 		archive->close(archive);
102 	} else {
103 		struct VFile* vf = VFileOpen(path, O_RDONLY);
104 		if (!vf) {
105 			return NULL;
106 		}
107 		core = mCoreFindVF(vf);
108 		vf->close(vf);
109 	}
110 	if (core) {
111 		return core;
112 	}
113 	return NULL;
114 }
115 
mCoreLoadFile(struct mCore * core,const char * path)116 bool mCoreLoadFile(struct mCore* core, const char* path) {
117 #ifdef FIXED_ROM_BUFFER
118 	return mCorePreloadFile(core, path);
119 #else
120 	struct VFile* rom = mDirectorySetOpenPath(&core->dirs, path, core->isROM);
121 	if (!rom) {
122 		return false;
123 	}
124 
125 	bool ret = core->loadROM(core, rom);
126 	if (!ret) {
127 		rom->close(rom);
128 	}
129 	return ret;
130 #endif
131 }
132 
mCorePreloadVF(struct mCore * core,struct VFile * vf)133 bool mCorePreloadVF(struct mCore* core, struct VFile* vf) {
134 	return mCorePreloadVFCB(core, vf, NULL, NULL);
135 }
136 
mCorePreloadFile(struct mCore * core,const char * path)137 bool mCorePreloadFile(struct mCore* core, const char* path) {
138 	return mCorePreloadFileCB(core, path, NULL, NULL);
139 }
140 
mCorePreloadVFCB(struct mCore * core,struct VFile * vf,void (cb)(size_t,size_t,void *),void * context)141 bool mCorePreloadVFCB(struct mCore* core, struct VFile* vf, void (cb)(size_t, size_t, void*), void* context) {
142 	struct VFile* vfm;
143 	size_t size = vf->size(vf);
144 
145 #ifdef FIXED_ROM_BUFFER
146 	extern uint32_t* romBuffer;
147 	extern size_t romBufferSize;
148 	if (size > romBufferSize) {
149 		size = romBufferSize;
150 	}
151 	vfm = VFileFromMemory(romBuffer, size);
152 #else
153 	vfm = VFileMemChunk(NULL, size);
154 #endif
155 
156 	uint8_t buffer[2048];
157 	ssize_t read;
158 	size_t total = 0;
159 	vf->seek(vf, 0, SEEK_SET);
160 	while ((read = vf->read(vf, buffer, sizeof(buffer))) > 0) {
161 		vfm->write(vfm, buffer, read);
162 		total += read;
163 		if (cb) {
164 			cb(total, size, context);
165 		}
166 	}
167 	vf->close(vf);
168 	bool ret = core->loadROM(core, vfm);
169 	if (!ret) {
170 		vfm->close(vfm);
171 	}
172 	return ret;
173 }
174 
mCorePreloadFileCB(struct mCore * core,const char * path,void (cb)(size_t,size_t,void *),void * context)175 bool mCorePreloadFileCB(struct mCore* core, const char* path, void (cb)(size_t, size_t, void*), void* context) {
176 	struct VFile* rom = mDirectorySetOpenPath(&core->dirs, path, core->isROM);
177 	if (!rom) {
178 		return false;
179 	}
180 
181 	bool ret = mCorePreloadVFCB(core, rom, cb, context);
182 	if (!ret) {
183 		rom->close(rom);
184 	}
185 	return ret;
186 }
187 
mCoreAutoloadSave(struct mCore * core)188 bool mCoreAutoloadSave(struct mCore* core) {
189 	if (!core->dirs.save) {
190 		return false;
191 	}
192 	return core->loadSave(core, mDirectorySetOpenSuffix(&core->dirs, core->dirs.save, ".sav", O_CREAT | O_RDWR));
193 }
194 
mCoreAutoloadPatch(struct mCore * core)195 bool mCoreAutoloadPatch(struct mCore* core) {
196 	if (!core->dirs.patch) {
197 		return false;
198 	}
199 	return core->loadPatch(core, mDirectorySetOpenSuffix(&core->dirs, core->dirs.patch, ".ups", O_RDONLY)) ||
200 	       core->loadPatch(core, mDirectorySetOpenSuffix(&core->dirs, core->dirs.patch, ".ips", O_RDONLY)) ||
201 	       core->loadPatch(core, mDirectorySetOpenSuffix(&core->dirs, core->dirs.patch, ".bps", O_RDONLY));
202 }
203 
mCoreAutoloadCheats(struct mCore * core)204 bool mCoreAutoloadCheats(struct mCore* core) {
205 	bool success = true;
206 	int cheatAuto;
207 	if (!mCoreConfigGetIntValue(&core->config, "cheatAutoload", &cheatAuto) || cheatAuto) {
208 		struct VFile* vf = mDirectorySetOpenSuffix(&core->dirs, core->dirs.cheats, ".cheats", O_RDONLY);
209 		if (vf) {
210 			struct mCheatDevice* device = core->cheatDevice(core);
211 			success = mCheatParseFile(device, vf);
212 			vf->close(vf);
213 		}
214 	}
215 	if (!mCoreConfigGetIntValue(&core->config, "cheatAutosave", &cheatAuto) || cheatAuto) {
216 		struct mCheatDevice* device = core->cheatDevice(core);
217 		device->autosave = true;
218 	}
219 	return success;
220 }
221 
mCoreSaveState(struct mCore * core,int slot,int flags)222 bool mCoreSaveState(struct mCore* core, int slot, int flags) {
223 	struct VFile* vf = mCoreGetState(core, slot, true);
224 	if (!vf) {
225 		return false;
226 	}
227 	bool success = mCoreSaveStateNamed(core, vf, flags);
228 	vf->close(vf);
229 	if (success) {
230 		mLOG(STATUS, INFO, "State %i saved", slot);
231 	} else {
232 		mLOG(STATUS, INFO, "State %i failed to save", slot);
233 	}
234 
235 	return success;
236 }
237 
mCoreLoadState(struct mCore * core,int slot,int flags)238 bool mCoreLoadState(struct mCore* core, int slot, int flags) {
239 	struct VFile* vf = mCoreGetState(core, slot, false);
240 	if (!vf) {
241 		return false;
242 	}
243 	bool success = mCoreLoadStateNamed(core, vf, flags);
244 	vf->close(vf);
245 	if (success) {
246 		mLOG(STATUS, INFO, "State %i loaded", slot);
247 	} else {
248 		mLOG(STATUS, INFO, "State %i failed to load", slot);
249 	}
250 
251 	return success;
252 }
253 
mCoreGetState(struct mCore * core,int slot,bool write)254 struct VFile* mCoreGetState(struct mCore* core, int slot, bool write) {
255 	if (!core->dirs.state) {
256 		return NULL;
257 	}
258 	char name[PATH_MAX + 14]; // Quash warning
259 	snprintf(name, sizeof(name), "%s.ss%i", core->dirs.baseName, slot);
260 	return core->dirs.state->openFile(core->dirs.state, name, write ? (O_CREAT | O_TRUNC | O_RDWR) : O_RDONLY);
261 }
262 
mCoreDeleteState(struct mCore * core,int slot)263 void mCoreDeleteState(struct mCore* core, int slot) {
264 	char name[PATH_MAX + 14]; // Quash warning
265 	snprintf(name, sizeof(name), "%s.ss%i", core->dirs.baseName, slot);
266 	core->dirs.state->deleteFile(core->dirs.state, name);
267 }
268 
mCoreTakeScreenshot(struct mCore * core)269 void mCoreTakeScreenshot(struct mCore* core) {
270 #ifdef USE_PNG
271 	size_t stride;
272 	const void* pixels = 0;
273 	unsigned width, height;
274 	core->desiredVideoDimensions(core, &width, &height);
275 	struct VFile* vf;
276 #ifndef PSP2
277 	vf = VDirFindNextAvailable(core->dirs.screenshot, core->dirs.baseName, "-", ".png", O_CREAT | O_TRUNC | O_WRONLY);
278 #else
279 	vf = VFileMemChunk(0, 0);
280 #endif
281 	bool success = false;
282 	if (vf) {
283 		core->getPixels(core, &pixels, &stride);
284 		png_structp png = PNGWriteOpen(vf);
285 		png_infop info = PNGWriteHeader(png, width, height);
286 		success = PNGWritePixels(png, width, height, stride, pixels);
287 		PNGWriteClose(png, info);
288 #ifdef PSP2
289 		void* data = vf->map(vf, 0, 0);
290 		PhotoExportParam param = {
291 			0,
292 			NULL,
293 			NULL,
294 			NULL,
295 			{ 0 }
296 		};
297 		scePhotoExportFromData(data, vf->size(vf), &param, NULL, NULL, NULL, NULL, 0);
298 #endif
299 		vf->close(vf);
300 	}
301 	if (success) {
302 		mLOG(STATUS, INFO, "Screenshot saved");
303 		return;
304 	}
305 #else
306 	UNUSED(core);
307 #endif
308 	mLOG(STATUS, WARN, "Failed to take screenshot");
309 }
310 #endif
311 
mCoreInitConfig(struct mCore * core,const char * port)312 void mCoreInitConfig(struct mCore* core, const char* port) {
313 	mCoreConfigInit(&core->config, port);
314 }
315 
mCoreLoadConfig(struct mCore * core)316 void mCoreLoadConfig(struct mCore* core) {
317 #if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
318 	mCoreConfigLoad(&core->config);
319 #endif
320 	mCoreLoadForeignConfig(core, &core->config);
321 }
322 
mCoreLoadForeignConfig(struct mCore * core,const struct mCoreConfig * config)323 void mCoreLoadForeignConfig(struct mCore* core, const struct mCoreConfig* config) {
324 	mCoreConfigMap(config, &core->opts);
325 #if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
326 	mDirectorySetMapOptions(&core->dirs, &core->opts);
327 #endif
328 	if (core->opts.audioBuffers) {
329 		core->setAudioBufferSize(core, core->opts.audioBuffers);
330 	}
331 
332 	mCoreConfigCopyValue(&core->config, config, "cheatAutosave");
333 	mCoreConfigCopyValue(&core->config, config, "cheatAutoload");
334 
335 	core->loadConfig(core, config);
336 }
337 
mCoreSetRTC(struct mCore * core,struct mRTCSource * rtc)338 void mCoreSetRTC(struct mCore* core, struct mRTCSource* rtc) {
339 	core->rtc.custom = rtc;
340 	core->rtc.override = RTC_CUSTOM_START;
341 }
342 
mCoreGetMemoryBlock(struct mCore * core,uint32_t start,size_t * size)343 void* mCoreGetMemoryBlock(struct mCore* core, uint32_t start, size_t* size) {
344 	const struct mCoreMemoryBlock* blocks;
345 	size_t nBlocks = core->listMemoryBlocks(core, &blocks);
346 	size_t i;
347 	for (i = 0; i < nBlocks; ++i) {
348 		if (!(blocks[i].flags & mCORE_MEMORY_MAPPED)) {
349 			continue;
350 		}
351 		if (start < blocks[i].start) {
352 			continue;
353 		}
354 		if (start >= blocks[i].start + blocks[i].size) {
355 			continue;
356 		}
357 		uint8_t* out = core->getMemoryBlock(core, blocks[i].id, size);
358 		out += start - blocks[i].start;
359 		*size -= start - blocks[i].start;
360 		return out;
361 	}
362 	return NULL;
363 }
364 
365 #ifdef USE_ELF
mCoreLoadELF(struct mCore * core,struct ELF * elf)366 bool mCoreLoadELF(struct mCore* core, struct ELF* elf) {
367 	struct ELFProgramHeaders ph;
368 	ELFProgramHeadersInit(&ph, 0);
369 	ELFGetProgramHeaders(elf, &ph);
370 	size_t i;
371 	for (i = 0; i < ELFProgramHeadersSize(&ph); ++i) {
372 		size_t bsize, esize;
373 		Elf32_Phdr* phdr = ELFProgramHeadersGetPointer(&ph, i);
374 		void* block = mCoreGetMemoryBlock(core, phdr->p_paddr, &bsize);
375 		char* bytes = ELFBytes(elf, &esize);
376 		if (block && bsize >= phdr->p_filesz && esize > phdr->p_offset && esize >= phdr->p_filesz + phdr->p_offset) {
377 			memcpy(block, &bytes[phdr->p_offset], phdr->p_filesz);
378 		} else {
379 			ELFProgramHeadersDeinit(&ph);
380 			return false;
381 		}
382 	}
383 	ELFProgramHeadersDeinit(&ph);
384 	return true;
385 }
386 
387 #ifdef USE_DEBUGGERS
mCoreLoadELFSymbols(struct mDebuggerSymbols * symbols,struct ELF * elf)388 void mCoreLoadELFSymbols(struct mDebuggerSymbols* symbols, struct ELF* elf) {
389 	size_t symIndex = ELFFindSection(elf, ".symtab");
390 	size_t names = ELFFindSection(elf, ".strtab");
391 	Elf32_Shdr* symHeader = ELFGetSectionHeader(elf, symIndex);
392 	char* bytes = ELFBytes(elf, NULL);
393 
394 	Elf32_Sym* syms = (Elf32_Sym*) &bytes[symHeader->sh_offset];
395 	size_t i;
396 	for (i = 0; i * sizeof(*syms) < symHeader->sh_size; ++i) {
397 		if (!syms[i].st_name || ELF32_ST_TYPE(syms[i].st_info) == STT_FILE) {
398 			continue;
399 		}
400 		const char* name = ELFGetString(elf, names, syms[i].st_name);
401 		if (name[0] == '$') {
402 			continue;
403 		}
404 		mDebuggerSymbolAdd(symbols, name, syms[i].st_value, -1);
405 	}
406 }
407 #endif
408 #endif
409