all repos — mgba @ 1f156921732db400cfbb4a0ff3f8efc0faf5dd1e

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