all repos — mgba @ 7ebd2d6e7546b91217d6dba88d0d2d01d72f4905

mGBA Game Boy Advance Emulator

src/platform/python/_builder.py (view raw)

  1import cffi
  2import os, os.path
  3import shlex
  4import subprocess
  5import sys
  6
  7ffi = cffi.FFI()
  8pydir = os.path.dirname(os.path.abspath(__file__))
  9srcdir = os.path.join(pydir, "..", "..")
 10incdir = os.path.join(pydir, "..", "..", "..", "include")
 11bindir = os.environ.get("BINDIR", os.path.join(os.getcwd(), ".."))
 12
 13cpp = shlex.split(os.environ.get("CPP", "cc -E"))
 14cppflags = shlex.split(os.environ.get("CPPFLAGS", ""))
 15if __name__ == "__main__":
 16    cppflags.extend(sys.argv[1:])
 17cppflags.extend(["-I" + incdir, "-I" + srcdir, "-I" + bindir])
 18
 19ffi.set_source("mgba._pylib", """
 20#define static
 21#define inline
 22#include "flags.h"
 23#define OPAQUE_THREADING
 24#include <mgba/core/cache-set.h>
 25#include <mgba-util/common.h>
 26#include <mgba/core/core.h>
 27#include <mgba/core/map-cache.h>
 28#include <mgba/core/log.h>
 29#include <mgba/core/mem-search.h>
 30#include <mgba/core/thread.h>
 31#include <mgba/core/version.h>
 32#include <mgba/debugger/debugger.h>
 33#include <mgba/internal/arm/arm.h>
 34#include <mgba/internal/debugger/cli-debugger.h>
 35#include <mgba/internal/gba/gba.h>
 36#include <mgba/internal/gba/input.h>
 37#include <mgba/internal/gba/renderers/cache-set.h>
 38#include <mgba/internal/lr35902/lr35902.h>
 39#include <mgba/internal/gb/gb.h>
 40#include <mgba/internal/gb/renderers/cache-set.h>
 41#include <mgba-util/png-io.h>
 42#include <mgba-util/vfs.h>
 43
 44#define PYEXPORT
 45#include "platform/python/core.h"
 46#include "platform/python/log.h"
 47#include "platform/python/sio.h"
 48#include "platform/python/vfs-py.h"
 49#undef PYEXPORT
 50""", include_dirs=[incdir, srcdir],
 51     extra_compile_args=cppflags,
 52     libraries=["mgba"],
 53     library_dirs=[bindir],
 54     sources=[os.path.join(pydir, path) for path in ["vfs-py.c", "core.c", "log.c", "sio.c"]])
 55
 56preprocessed = subprocess.check_output(cpp + ["-fno-inline", "-P"] + cppflags + [os.path.join(pydir, "_builder.h")], universal_newlines=True)
 57
 58lines = []
 59for line in preprocessed.splitlines():
 60    line = line.strip()
 61    if line.startswith('#'):
 62        continue
 63    lines.append(line)
 64ffi.cdef('\n'.join(lines))
 65
 66preprocessed = subprocess.check_output(cpp + ["-fno-inline", "-P"] + cppflags + [os.path.join(pydir, "lib.h")], universal_newlines=True)
 67
 68lines = []
 69for line in preprocessed.splitlines():
 70    line = line.strip()
 71    if line.startswith('#'):
 72        continue
 73    lines.append(line)
 74ffi.embedding_api('\n'.join(lines))
 75
 76ffi.embedding_init_code("""
 77    import os, os.path
 78    venv = os.getenv('VIRTUAL_ENV')
 79    if venv:
 80        activate = os.path.join(venv, 'bin', 'activate_this.py')
 81        exec(compile(open(activate, "rb").read(), activate, 'exec'), dict(__file__=activate))
 82    from mgba._pylib import ffi, lib
 83    symbols = {}
 84    globalSyms = {
 85        'symbols': symbols
 86    }
 87    pendingCode = []
 88
 89    @ffi.def_extern()
 90    def mPythonSetDebugger(debugger):
 91        from mgba.debugger import NativeDebugger, CLIDebugger
 92        oldDebugger = globalSyms.get('debugger')
 93        if oldDebugger and oldDebugger._native == debugger:
 94            return
 95        if oldDebugger and not debugger:
 96            del globalSyms['debugger']
 97            return
 98        if debugger.type == lib.DEBUGGER_CLI:
 99            debugger = CLIDebugger(debugger)
100        else:
101            debugger = NativeDebugger(debugger)
102        globalSyms['debugger'] = debugger
103
104    @ffi.def_extern()
105    def mPythonLoadScript(name, vf):
106        from mgba.vfs import VFile
107        vf = VFile(vf)
108        name = ffi.string(name)
109        source = vf.readAll().decode('utf-8')
110        try:
111            code = compile(source, name, 'exec')
112            pendingCode.append(code)
113        except:
114            return False
115        return True
116
117    @ffi.def_extern()
118    def mPythonRunPending():
119        global pendingCode
120        for code in pendingCode:
121            exec(code, globalSyms, {})
122        pendingCode = []
123
124    @ffi.def_extern()
125    def mPythonDebuggerEntered(reason, info):
126        debugger = globalSyms['debugger']
127        if not debugger:
128            return
129        if info == ffi.NULL:
130            info = None
131        for cb in debugger._cbs:
132            cb(reason, info)
133
134    @ffi.def_extern()
135    def mPythonLookupSymbol(name, outptr):
136        name = ffi.string(name).decode('utf-8')
137        if name not in symbols:
138            return False
139        sym = symbols[name]
140        val = None
141        try:
142            val = int(sym)
143        except:
144            try:
145                val = sym()
146            except:
147                pass
148        if val is None:
149            return False
150        try:
151            outptr[0] = ffi.cast('int32_t', val)
152            return True
153        except:
154            return False
155""")
156
157if __name__ == "__main__":
158    ffi.emit_c_code("lib.c")