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/sm83/sm83.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 uint8_t commandActive;
78 uint8_t alarm1[3];
79 RTCCommandData command;
80 RTCStatus2 status2;
81 uint8_t freeReg;
82 RTCControl control;
83 uint8_t alarm2[3];
84 uint8_t time[7];
85};""", packed=True)
86
87preprocessed = subprocess.check_output(cpp + ["-fno-inline", "-P"] + cppflags + [os.path.join(pydir, "lib.h")], universal_newlines=True)
88
89lines = []
90for line in preprocessed.splitlines():
91 line = line.strip()
92 if line.startswith('#'):
93 continue
94 lines.append(line)
95ffi.embedding_api('\n'.join(lines))
96
97ffi.embedding_init_code("""
98 import os, os.path
99 from mgba._pylib import ffi, lib
100 symbols = {}
101 globalSyms = {
102 'symbols': symbols
103 }
104 pendingCode = []
105
106 @ffi.def_extern()
107 def mPythonSetDebugger(debugger):
108 from mgba.debugger import NativeDebugger, CLIDebugger
109 oldDebugger = globalSyms.get('debugger')
110 if oldDebugger and oldDebugger._native == debugger:
111 return
112 if oldDebugger and not debugger:
113 del globalSyms['debugger']
114 return
115 if debugger.type == lib.DEBUGGER_CLI:
116 debugger = CLIDebugger(debugger)
117 else:
118 debugger = NativeDebugger(debugger)
119 globalSyms['debugger'] = debugger
120
121 @ffi.def_extern()
122 def mPythonLoadScript(name, vf):
123 from mgba.vfs import VFile
124 vf = VFile(vf)
125 name = ffi.string(name)
126 source = vf.read_all().decode('utf-8')
127 try:
128 code = compile(source, name, 'exec')
129 pendingCode.append(code)
130 except:
131 return False
132 return True
133
134 @ffi.def_extern()
135 def mPythonRunPending():
136 global pendingCode
137 for code in pendingCode:
138 exec(code, globalSyms, {})
139 pendingCode = []
140
141 @ffi.def_extern()
142 def mPythonDebuggerEntered(reason, info):
143 debugger = globalSyms['debugger']
144 if not debugger:
145 return
146 if info == ffi.NULL:
147 info = None
148 for cb in debugger._cbs:
149 cb(reason, info)
150
151 @ffi.def_extern()
152 def mPythonLookupSymbol(name, outptr):
153 name = ffi.string(name).decode('utf-8')
154 if name not in symbols:
155 return False
156 sym = symbols[name]
157 val = None
158 try:
159 val = int(sym)
160 except:
161 try:
162 val = sym()
163 except:
164 pass
165 if val is None:
166 return False
167 try:
168 outptr[0] = ffi.cast('int32_t', val)
169 return True
170 except:
171 return False
172""")
173
174if __name__ == "__main__":
175 ffi.emit_c_code("lib.c")