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