arm_utils: relax alignment requirements
[pcsx_rearmed.git] / frontend / main.c
1 /*
2  * (C) notaz, 2010-2011
3  *
4  * This work is licensed under the terms of the GNU GPLv2 or later.
5  * See the COPYING file in the top-level directory.
6  */
7
8 #include <stdio.h>
9 #include <string.h>
10 #include <stdarg.h>
11 #include <dlfcn.h>
12 #include <sys/stat.h>
13 #include <sys/types.h>
14 #include <unistd.h>
15 #include <signal.h>
16 #include <time.h>
17
18 #include "main.h"
19 #include "plugin.h"
20 #include "plugin_lib.h"
21 #include "pcnt.h"
22 #include "menu.h"
23 #include "../libpcsxcore/misc.h"
24 #include "../libpcsxcore/new_dynarec/new_dynarec.h"
25 #include "../plugins/cdrcimg/cdrcimg.h"
26 #include "common/plat.h"
27 #include "common/input.h"
28 #include "common/readpng.h"
29
30 int ready_to_go;
31 unsigned long gpuDisp;
32 char cfgfile_basename[MAXPATHLEN];
33 static char *(*real_getenv)(const char *name);
34 int state_slot;
35 enum sched_action emu_action, emu_action_old;
36 char hud_msg[64];
37 int hud_new_msg;
38
39 // from softgpu plugin
40 extern int UseFrameSkip;
41
42 static void make_path(char *buf, size_t size, const char *dir, const char *fname)
43 {
44         if (fname)
45                 snprintf(buf, size, ".%s%s", dir, fname);
46         else
47                 snprintf(buf, size, ".%s", dir);
48 }
49 #define MAKE_PATH(buf, dir, fname) \
50         make_path(buf, sizeof(buf), dir, fname)
51
52 static void create_profile_dir(const char *directory) {
53         char path[MAXPATHLEN];
54
55         MAKE_PATH(path, directory, NULL);
56         mkdir(path, S_IRWXU | S_IRWXG);
57 }
58
59 static void CheckSubDir() {
60         // make sure that ~/.pcsx exists
61         create_profile_dir(PCSX_DOT_DIR);
62
63         create_profile_dir(BIOS_DIR);
64         create_profile_dir(MEMCARD_DIR);
65         create_profile_dir(STATES_DIR);
66         create_profile_dir(PLUGINS_DIR);
67         create_profile_dir(PLUGINS_CFG_DIR);
68         create_profile_dir(CHEATS_DIR);
69         create_profile_dir(PATCHES_DIR);
70         create_profile_dir(PCSX_DOT_DIR "cfg");
71         create_profile_dir("/screenshots/");
72 }
73
74 static int get_gameid_filename(char *buf, int size, const char *fmt, int i) {
75         char trimlabel[33];
76         int j;
77
78         strncpy(trimlabel, CdromLabel, 32);
79         trimlabel[32] = 0;
80         for (j = 31; j >= 0; j--)
81                 if (trimlabel[j] == ' ')
82                         trimlabel[j] = 0;
83                 else
84                         continue;
85
86         snprintf(buf, size, fmt, trimlabel, CdromId, i);
87
88         return 0;
89 }
90
91 void set_cd_image(const char *fname)
92 {
93         const char *ext = NULL;
94         
95         if (fname != NULL)
96                 ext = strrchr(fname, '.');
97
98         if (ext && (
99             strcasecmp(ext, ".z") == 0 || strcasecmp(ext, ".bz") == 0 ||
100             strcasecmp(ext, ".znx") == 0 || strcasecmp(ext, ".pbp") == 0)) {
101                 SetIsoFile(NULL);
102                 cdrcimg_set_fname(fname);
103                 strcpy(Config.Cdr, "builtin_cdrcimg");
104         } else {
105                 SetIsoFile(fname);
106                 strcpy(Config.Cdr, "builtin_cdr");
107         }
108 }
109
110 static void set_default_paths(void)
111 {
112         MAKE_PATH(Config.Mcd1, MEMCARD_DIR, "card1.mcd");
113         MAKE_PATH(Config.Mcd2, MEMCARD_DIR, "card2.mcd");
114         strcpy(Config.BiosDir, "bios");
115
116         strcpy(Config.PluginsDir, "plugins");
117         strcpy(Config.Gpu, "builtin_gpu");
118         strcpy(Config.Spu, "builtin_spu");
119         strcpy(Config.Cdr, "builtin_cdr");
120         strcpy(Config.Pad1, "builtin_pad");
121         strcpy(Config.Pad2, "builtin_pad");
122         strcpy(Config.Net, "Disabled");
123         Config.PsxAuto = 1;
124
125         snprintf(Config.PatchesDir, sizeof(Config.PatchesDir), "." PATCHES_DIR);
126 }
127
128 void do_emu_action(void)
129 {
130         char buf[MAXPATHLEN];
131         int ret;
132
133         emu_action_old = emu_action;
134
135         switch (emu_action) {
136         case SACTION_NONE:
137                 return;
138         case SACTION_ENTER_MENU:
139                 menu_loop();
140                 return;
141         case SACTION_LOAD_STATE:
142                 ret = emu_load_state(state_slot);
143                 snprintf(hud_msg, sizeof(hud_msg), ret == 0 ? "LOADED" : "FAIL!");
144                 break;
145         case SACTION_SAVE_STATE:
146                 ret = emu_save_state(state_slot);
147                 snprintf(hud_msg, sizeof(hud_msg), ret == 0 ? "SAVED" : "FAIL!");
148                 break;
149         case SACTION_NEXT_SSLOT:
150                 state_slot++;
151                 if (state_slot > 9)
152                         state_slot = 0;
153                 goto do_state_slot;
154         case SACTION_PREV_SSLOT:
155                 state_slot--;
156                 if (state_slot < 0)
157                         state_slot = 9;
158                 goto do_state_slot;
159         case SACTION_TOGGLE_FSKIP:
160                 UseFrameSkip ^= 1;
161                 snprintf(hud_msg, sizeof(hud_msg), "FRAMESKIP %s",
162                         UseFrameSkip ? "ON" : "OFF");
163                 break;
164         case SACTION_SCREENSHOT:
165                 {
166                         void *scrbuf;
167                         int w, h, bpp;
168                         time_t t = time(NULL);
169                         struct tm *tb = localtime(&t);
170                         int ti = tb->tm_yday * 1000000 + tb->tm_hour * 10000 +
171                                 tb->tm_min * 100 + tb->tm_sec;
172
173                         scrbuf = pl_prepare_screenshot(&w, &h, &bpp);
174                         get_gameid_filename(buf, sizeof(buf),
175                                 "screenshots/%.32s-%.9s.%d.png", ti);
176                         ret = -1;
177                         if (scrbuf != 0 && bpp == 16)
178                                 ret = writepng(buf, scrbuf, w, h);
179                         if (ret == 0)
180                                 snprintf(hud_msg, sizeof(hud_msg), "SCREENSHOT TAKEN");
181                         break;
182                 }
183         }
184         hud_new_msg = 3;
185         return;
186
187 do_state_slot:
188         snprintf(hud_msg, sizeof(hud_msg), "STATE SLOT %d [%s]", state_slot,
189                 emu_check_state(state_slot) == 0 ? "USED" : "FREE");
190         hud_new_msg = 3;
191 }
192
193 int main(int argc, char *argv[])
194 {
195         void *tmp;
196
197         tmp = dlopen("/lib/libdl.so.2", RTLD_LAZY);
198         if (tmp == NULL)
199                 tmp = dlopen("/lib32/libdl.so.2", RTLD_LAZY);
200         if (tmp != NULL)
201                 real_getenv = dlsym(tmp, "getenv");
202         if (real_getenv == NULL) {
203                 fprintf(stderr, "%s\n", dlerror());
204                 return 1;
205         }
206         dlclose(tmp);
207
208         // what is the name of the config file?
209         // it may be redefined by -cfg on the command line
210         strcpy(cfgfile_basename, "pcsx.cfg");
211
212         emuLog = stdout;
213         SetIsoFile(NULL);
214
215         memset(&Config, 0, sizeof(Config));
216
217         CheckSubDir();
218         set_default_paths();
219         strcpy(Config.Bios, "HLE");
220
221 #ifdef MAEMO
222         extern int maemo_main(int argc, char **argv);
223         return maemo_main(argc, argv);
224 #else
225         char file[MAXPATHLEN] = "";
226         char path[MAXPATHLEN];
227         const char *cdfile = NULL;
228         const char *loadst_f = NULL;
229         int psxout = 0;
230         int loadst = 0;
231         int i;
232
233         // read command line options
234         for (i = 1; i < argc; i++) {
235                      if (!strcmp(argv[i], "-psxout")) psxout = 1;
236                 else if (!strcmp(argv[i], "-load")) loadst = atol(argv[++i]);
237                 else if (!strcmp(argv[i], "-cfg")) {
238                         if (i+1 >= argc) break;
239                         strncpy(cfgfile_basename, argv[++i], MAXPATHLEN-100);   /* TODO buffer overruns */
240                         printf("Using config file %s.\n", cfgfile_basename);
241                 }
242                 else if (!strcmp(argv[i], "-cdfile")) {
243                         char isofilename[MAXPATHLEN];
244
245                         if (i+1 >= argc) break;
246                         strncpy(isofilename, argv[++i], MAXPATHLEN);
247                         if (isofilename[0] != '/') {
248                                 getcwd(path, MAXPATHLEN);
249                                 if (strlen(path) + strlen(isofilename) + 1 < MAXPATHLEN) {
250                                         strcat(path, "/");
251                                         strcat(path, isofilename);
252                                         strcpy(isofilename, path);
253                                 } else
254                                         isofilename[0] = 0;
255                         }
256
257                         cdfile = isofilename;
258                 }
259                 else if (!strcmp(argv[i], "-loadf")) {
260                         if (i+1 >= argc) break;
261                         loadst_f = argv[++i];
262                 }
263                 else if (!strcmp(argv[i], "-h") ||
264                          !strcmp(argv[i], "-help") ||
265                          !strcmp(argv[i], "--help")) {
266                          printf(PACKAGE_NAME " " PACKAGE_VERSION "\n");
267                          printf("%s\n", _(
268                                                         " pcsx [options] [file]\n"
269                                                         "\toptions:\n"
270                                                         "\t-cdfile FILE\tRuns a CD image file\n"
271                                                         "\t-nogui\t\tDon't open the GTK GUI\n"
272                                                         "\t-cfg FILE\tLoads desired configuration file (default: ~/.pcsx/pcsx.cfg)\n"
273                                                         "\t-psxout\t\tEnable PSX output\n"
274                                                         "\t-load STATENUM\tLoads savestate STATENUM (1-5)\n"
275                                                         "\t-h -help\tDisplay this message\n"
276                                                         "\tfile\t\tLoads file\n"));
277                          return 0;
278                 } else {
279                         strncpy(file, argv[i], MAXPATHLEN);
280                         if (file[0] != '/') {
281                                 getcwd(path, MAXPATHLEN);
282                                 if (strlen(path) + strlen(file) + 1 < MAXPATHLEN) {
283                                         strcat(path, "/");
284                                         strcat(path, file);
285                                         strcpy(file, path);
286                                 } else
287                                         file[0] = 0;
288                         }
289                 }
290         }
291
292         if (cdfile)
293                 set_cd_image(cdfile);
294
295         if (SysInit() == -1)
296                 return 1;
297
298         // frontend stuff
299         in_init();
300         //in_probe();
301         plat_init();
302         menu_init(); // loads config
303
304         if (psxout)
305                 Config.PsxOut = 1;
306
307         if (LoadPlugins() == -1) {
308                 // FIXME: this recovery doesn't work, just delete bad config and bail out
309                 // SysMessage("could not load plugins, retrying with defaults\n");
310                 set_default_paths();
311                 snprintf(path, sizeof(path), "." PCSX_DOT_DIR "%s", cfgfile_basename);
312                 remove(path);
313                 SysMessage("Failed loading plugins!");
314                 return 1;
315         }
316         pcnt_hook_plugins();
317
318         if (OpenPlugins() == -1) {
319                 return 1;
320         }
321         plugin_call_rearmed_cbs();
322
323         CheckCdrom();
324         SysReset();
325
326         if (file[0] != '\0') {
327                 if (Load(file) != -1)
328                         ready_to_go = 1;
329         } else {
330                 if (cdfile) {
331                         if (LoadCdrom() == -1) {
332                                 ClosePlugins();
333                                 printf(_("Could not load CD-ROM!\n"));
334                                 return -1;
335                         }
336                         ready_to_go = 1;
337                 }
338         }
339
340         if (ready_to_go) {
341                 menu_prepare_emu();
342
343                 // If a state has been specified, then load that
344                 if (loadst) {
345                         int ret = emu_load_state(loadst - 1);
346                         printf("%s state %d\n", ret ? "failed to load" : "loaded", loadst);
347                 }
348                 if (loadst_f) {
349                         int ret = LoadState(loadst_f);
350                         printf("%s state file: %s\n", ret ? "failed to load" : "loaded", loadst_f);
351                 }
352         }
353         else
354                 menu_loop();
355
356         pl_start_watchdog();
357
358         while (1)
359         {
360                 stop = 0;
361                 emu_action = SACTION_NONE;
362
363                 psxCpu->Execute();
364                 if (emu_action != SACTION_NONE)
365                         do_emu_action();
366         }
367
368         return 0;
369 #endif
370 }
371
372 int SysInit() {
373         if (EmuInit() == -1) {
374                 printf("PSX emulator couldn't be initialized.\n");
375                 return -1;
376         }
377
378         LoadMcds(Config.Mcd1, Config.Mcd2);     /* TODO Do we need to have this here, or in the calling main() function?? */
379
380         if (Config.Debug) {
381                 StartDebugger();
382         }
383
384         return 0;
385 }
386
387 void SysRunGui() {
388         printf("SysRunGui\n");
389 }
390
391 void StartGui() {
392         printf("StartGui\n");
393 }
394
395 static void dummy_lace()
396 {
397 }
398
399 void SysReset() {
400         // rearmed hack: EmuReset() runs some code when real BIOS is used,
401         // but we usually do reset from menu while GPU is not open yet,
402         // so we need to prevent updateLace() call..
403         void *real_lace = GPU_updateLace;
404         GPU_updateLace = dummy_lace;
405
406         EmuReset();
407
408         // hmh core forgets this
409         CDR_stop();
410
411         GPU_updateLace = real_lace;
412 }
413
414 void SysClose() {
415         EmuShutdown();
416         ReleasePlugins();
417
418         StopDebugger();
419
420         if (emuLog != NULL) fclose(emuLog);
421 }
422
423 void SysUpdate() {
424 }
425
426 void OnFile_Exit() {
427         printf("OnFile_Exit\n");
428 #ifndef MAEMO
429         menu_finish();
430 #endif
431         SysClose();
432         plat_finish();
433         exit(0);
434 }
435
436 int get_state_filename(char *buf, int size, int i) {
437         return get_gameid_filename(buf, size,
438                 "." STATES_DIR "%.32s-%.9s.%3.3d", i);
439 }
440
441 int emu_check_state(int slot)
442 {
443         char fname[MAXPATHLEN];
444         int ret;
445
446         ret = get_state_filename(fname, sizeof(fname), slot);
447         if (ret != 0)
448                 return ret;
449
450         return CheckState(fname);
451 }
452
453 int emu_save_state(int slot)
454 {
455         char fname[MAXPATHLEN];
456         int ret;
457
458         ret = get_state_filename(fname, sizeof(fname), slot);
459         if (ret != 0)
460                 return ret;
461
462         return SaveState(fname);
463 }
464
465 int emu_load_state(int slot)
466 {
467         char fname[MAXPATHLEN];
468         int ret;
469
470         ret = get_state_filename(fname, sizeof(fname), slot);
471         if (ret != 0)
472                 return ret;
473
474         return LoadState(fname);
475 }
476
477 void SysPrintf(const char *fmt, ...) {
478         va_list list;
479         char msg[512];
480
481         va_start(list, fmt);
482         vsprintf(msg, fmt, list);
483         va_end(list);
484
485         fprintf(emuLog, "%s", msg);
486 }
487
488 void SysMessage(const char *fmt, ...) {
489         va_list list;
490         char msg[512];
491
492         va_start(list, fmt);
493         vsprintf(msg, fmt, list);
494         va_end(list);
495
496         if (msg[strlen(msg) - 1] == '\n')
497                 msg[strlen(msg) - 1] = 0;
498
499         fprintf(stderr, "%s\n", msg);
500 }
501
502 static void SignalExit(int sig) {
503         ClosePlugins();
504         OnFile_Exit();
505 }
506
507 #define PARSEPATH(dst, src) \
508         ptr = src + strlen(src); \
509         while (*ptr != '\\' && ptr != src) ptr--; \
510         if (ptr != src) { \
511                 strcpy(dst, ptr+1); \
512         }
513
514 static int _OpenPlugins(void) {
515         int ret;
516
517         signal(SIGINT, SignalExit);
518         signal(SIGPIPE, SignalExit);
519
520         GPU_clearDynarec(clearDynarec);
521
522         ret = CDR_open();
523         if (ret < 0) { SysMessage(_("Error opening CD-ROM plugin!")); return -1; }
524         ret = SPU_open();
525         if (ret < 0) { SysMessage(_("Error opening SPU plugin!")); return -1; }
526         SPU_registerCallback(SPUirq);
527         // pcsx-rearmed: we handle gpu elsewhere
528         //ret = GPU_open(&gpuDisp, "PCSX", NULL);
529         //if (ret < 0) { SysMessage(_("Error opening GPU plugin!")); return -1; }
530         ret = PAD1_open(&gpuDisp);
531         if (ret < 0) { SysMessage(_("Error opening Controller 1 plugin!")); return -1; }
532         ret = PAD2_open(&gpuDisp);
533         if (ret < 0) { SysMessage(_("Error opening Controller 2 plugin!")); return -1; }
534
535         if (Config.UseNet && !NetOpened) {
536                 netInfo info;
537                 char path[MAXPATHLEN];
538                 char dotdir[MAXPATHLEN];
539
540                 MAKE_PATH(dotdir, "/.pcsx/plugins/", NULL);
541
542                 strcpy(info.EmuName, "PCSX " PACKAGE_VERSION);
543                 strncpy(info.CdromID, CdromId, 9);
544                 strncpy(info.CdromLabel, CdromLabel, 9);
545                 info.psxMem = psxM;
546                 info.GPU_showScreenPic = GPU_showScreenPic;
547                 info.GPU_displayText = GPU_displayText;
548                 info.GPU_showScreenPic = GPU_showScreenPic;
549                 info.PAD_setSensitive = PAD1_setSensitive;
550                 sprintf(path, "%s%s", Config.BiosDir, Config.Bios);
551                 strcpy(info.BIOSpath, path);
552                 strcpy(info.MCD1path, Config.Mcd1);
553                 strcpy(info.MCD2path, Config.Mcd2);
554                 sprintf(path, "%s%s", dotdir, Config.Gpu);
555                 strcpy(info.GPUpath, path);
556                 sprintf(path, "%s%s", dotdir, Config.Spu);
557                 strcpy(info.SPUpath, path);
558                 sprintf(path, "%s%s", dotdir, Config.Cdr);
559                 strcpy(info.CDRpath, path);
560                 NET_setInfo(&info);
561
562                 ret = NET_open(&gpuDisp);
563                 if (ret < 0) {
564                         if (ret == -2) {
565                                 // -2 is returned when something in the info
566                                 // changed and needs to be synced
567                                 char *ptr;
568
569                                 PARSEPATH(Config.Bios, info.BIOSpath);
570                                 PARSEPATH(Config.Gpu,  info.GPUpath);
571                                 PARSEPATH(Config.Spu,  info.SPUpath);
572                                 PARSEPATH(Config.Cdr,  info.CDRpath);
573
574                                 strcpy(Config.Mcd1, info.MCD1path);
575                                 strcpy(Config.Mcd2, info.MCD2path);
576                                 return -2;
577                         } else {
578                                 Config.UseNet = FALSE;
579                         }
580                 } else {
581                         if (NET_queryPlayer() == 1) {
582                                 if (SendPcsxInfo() == -1) Config.UseNet = FALSE;
583                         } else {
584                                 if (RecvPcsxInfo() == -1) Config.UseNet = FALSE;
585                         }
586                 }
587                 NetOpened = TRUE;
588         } else if (Config.UseNet) {
589                 NET_resume();
590         }
591
592         return 0;
593 }
594
595 int OpenPlugins() {
596         int ret;
597
598         while ((ret = _OpenPlugins()) == -2) {
599                 ReleasePlugins();
600                 LoadMcds(Config.Mcd1, Config.Mcd2);
601                 if (LoadPlugins() == -1) return -1;
602         }
603         return ret;
604 }
605
606 void ClosePlugins() {
607         int ret;
608
609         signal(SIGINT, SIG_DFL);
610         signal(SIGPIPE, SIG_DFL);
611         ret = CDR_close();
612         if (ret < 0) { SysMessage(_("Error closing CD-ROM plugin!")); return; }
613         ret = SPU_close();
614         if (ret < 0) { SysMessage(_("Error closing SPU plugin!")); return; }
615         ret = PAD1_close();
616         if (ret < 0) { SysMessage(_("Error closing Controller 1 Plugin!")); return; }
617         ret = PAD2_close();
618         if (ret < 0) { SysMessage(_("Error closing Controller 2 plugin!")); return; }
619         // pcsx-rearmed: we handle gpu elsewhere
620         //ret = GPU_close();
621         //if (ret < 0) { SysMessage(_("Error closing GPU plugin!")); return; }
622
623         if (Config.UseNet) {
624                 NET_pause();
625         }
626 }
627
628 #if 1
629 /* this is to avoid having to hack every plugin to stop using $HOME */
630 char *getenv(const char *name)
631 {
632         static char ret[8] = ".";
633
634         if (name && strcmp(name, "HOME") == 0 &&
635                         ((int)name >> 28) == 0) // HACK: let libs find home
636                 return ret;
637
638         return real_getenv(name);
639 }
640 #endif
641
642 /* we hook statically linked plugins here */
643 static const char *builtin_plugins[] = {
644         "builtin_gpu", "builtin_spu", "builtin_cdr", "builtin_pad",
645         "builtin_cdrcimg",
646 };
647
648 static const int builtin_plugin_ids[] = {
649         PLUGIN_GPU, PLUGIN_SPU, PLUGIN_CDR, PLUGIN_PAD,
650         PLUGIN_CDRCIMG,
651 };
652
653 void *SysLoadLibrary(const char *lib) {
654         const char *tmp = strrchr(lib, '/');
655         void *ret;
656         int i;
657
658         printf("plugin: %s\n", lib);
659
660         if (tmp != NULL) {
661                 tmp++;
662                 for (i = 0; i < ARRAY_SIZE(builtin_plugins); i++)
663                         if (strcmp(tmp, builtin_plugins[i]) == 0)
664                                 return (void *)(long)(PLUGIN_DL_BASE + builtin_plugin_ids[i]);
665         }
666
667 #if defined(__x86_64__) || defined(__i386__)
668         // convenience hack
669         char name[MAXPATHLEN];
670         snprintf(name, sizeof(name), "%s.x86", lib);
671         lib = name;
672 #endif
673
674         ret = dlopen(lib, RTLD_NOW);
675         if (ret == NULL)
676                 fprintf(stderr, "dlopen: %s\n", dlerror());
677         return ret;
678 }
679
680 void *SysLoadSym(void *lib, const char *sym) {
681         unsigned int plugid = (unsigned int)(long)lib;
682
683         if (PLUGIN_DL_BASE <= plugid && plugid < PLUGIN_DL_BASE + ARRAY_SIZE(builtin_plugins))
684                 return plugin_link(plugid - PLUGIN_DL_BASE, sym);
685
686         return dlsym(lib, sym);
687 }
688
689 const char *SysLibError() {
690         return dlerror();
691 }
692
693 void SysCloseLibrary(void *lib) {
694         unsigned int plugid = (unsigned int)(long)lib;
695
696         if (PLUGIN_DL_BASE <= plugid && plugid < PLUGIN_DL_BASE + ARRAY_SIZE(builtin_plugins))
697                 return;
698
699         dlclose(lib);
700 }
701