all repos — mgba @ 448bc200c36c68a1250a2eb0394f5b90a2f75bed

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