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#include "flags.h"
22#define OPAQUE_THREADING
23#include <mgba/core/cache-set.h>
24#include <mgba-util/common.h>
25#include <mgba/core/core.h>
26#include <mgba/core/map-cache.h>
27#include <mgba/core/log.h>
28#include <mgba/core/mem-search.h>
29#include <mgba/core/thread.h>
30#include <mgba/core/version.h>
31#include <mgba/debugger/debugger.h>
32#include <mgba/gba/interface.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 runtime_library_dirs=[libdir],
55 sources=[os.path.join(pydir, path) for path in ["vfs-py.c", "core.c", "log.c", "sio.c"]])
56
57preprocessed = subprocess.check_output(cpp + ["-fno-inline", "-P"] + cppflags + [os.path.join(pydir, "_builder.h")], universal_newlines=True)
58
59lines = []
60for line in preprocessed.splitlines():
61 line = line.strip()
62 if line.startswith('#'):
63 continue
64 lines.append(line)
65ffi.cdef('\n'.join(lines))
66
67preprocessed = subprocess.check_output(cpp + ["-fno-inline", "-P"] + cppflags + [os.path.join(pydir, "lib.h")], universal_newlines=True)
68
69lines = []
70for line in preprocessed.splitlines():
71 line = line.strip()
72 if line.startswith('#'):
73 continue
74 lines.append(line)
75ffi.embedding_api('\n'.join(lines))
76
77ffi.embedding_init_code("""
78 import os, os.path
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.read_all().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")