Debian Codegraph @

lib_pypy/cffi/verifier.py

raw symbols SCIP
1 #
2 # DEPRECATED: implementation for ffi.verify()
3 #
4 import sys, os, binascii, shutil, io, threading
5 from . import __version_verifier_modules__
6 from . import ffiplatform
7 from .error import VerificationError
8
9 if sys.version_info >= (3, 3):
10 import importlib.machinery
11 def _extension_suffixes():
12 return importlib.machinery.EXTENSION_SUFFIXES[:]
13 else:
14 import imp
15 def _extension_suffixes():
16 return [suffix for suffix, _, type in imp.get_suffixes()
17 if type == imp.C_EXTENSION]
18
19
20 if sys.version_info >= (3,):
21 NativeIO = io.StringIO
22 else:
23 class NativeIO(io.BytesIO):
24 def write(self, s):
25 if isinstance(s, unicode):
26 s = s.encode('ascii')
27 super(NativeIO, self).write(s)
28
29
30 class Verifier(object):
31
32 def __init__(self, ffi, preamble, tmpdir=None, modulename=None,
33 ext_package=None, tag='', force_generic_engine=False,
34 source_extension='.c', flags=None, relative_to=None, **kwds):
35 if ffi._parser._uses_new_feature:
36 raise VerificationError(
37 "feature not supported with ffi.verify(), but only "
38 "with ffi.set_source(): %s" % (ffi._parser._uses_new_feature,))
39 self.ffi = ffi
40 self.preamble = preamble
41 if not modulename:
42 flattened_kwds = ffiplatform.flatten(kwds)
43 vengine_class = _locate_engine_class(ffi, force_generic_engine)
44 self._vengine = vengine_class(self)
45 self._vengine.patch_extension_kwds(kwds)
46 self.flags = flags
47 self.kwds = self.make_relative_to(kwds, relative_to)
48 #
49 if modulename:
50 if tag:
51 raise TypeError("can't specify both 'modulename' and 'tag'")
52 else:
53 key = '\x00'.join(['%d.%d' % sys.version_info[:2],
54 __version_verifier_modules__,
55 preamble, flattened_kwds] +
56 ffi._cdefsources)
57 if sys.version_info >= (3,):
58 key = key.encode('utf-8')
59 k1 = hex(binascii.crc32(key[0::2]) & 0xffffffff)
60 k1 = k1.lstrip('0x').rstrip('L')
61 k2 = hex(binascii.crc32(key[1::2]) & 0xffffffff)
62 k2 = k2.lstrip('0').rstrip('L')
63 modulename = '_cffi_%s_%s%s%s' % (tag, self._vengine._class_key,
64 k1, k2)
65 suffix = _get_so_suffixes()[0]
66 self.tmpdir = tmpdir or _caller_dir_pycache()
67 self.sourcefilename = os.path.join(self.tmpdir, modulename + source_extension)
68 self.modulefilename = os.path.join(self.tmpdir, modulename + suffix)
69 self.ext_package = ext_package
70 self._has_source = False
71 self._has_module = False
72
73 def write_source(self, file=None):
74 """Write the C source code. It is produced in 'self.sourcefilename',
75 which can be tweaked beforehand."""
76 with self.ffi._lock:
77 if self._has_source and file is None:
78 raise VerificationError(
79 "source code already written")
80 self._write_source(file)
81
82 def compile_module(self):
83 """Write the C source code (if not done already) and compile it.
84 This produces a dynamic link library in 'self.modulefilename'."""
85 with self.ffi._lock:
86 if self._has_module:
87 raise VerificationError("module already compiled")
88 if not self._has_source:
89 self._write_source()
90 self._compile_module()
91
92 def load_library(self):
93 """Get a C module from this Verifier instance.
94 Returns an instance of a FFILibrary class that behaves like the
95 objects returned by ffi.dlopen(), but that delegates all
96 operations to the C module. If necessary, the C code is written
97 and compiled first.
98 """
99 with self.ffi._lock:
100 if not self._has_module:
101 self._locate_module()
102 if not self._has_module:
103 if not self._has_source:
104 self._write_source()
105 self._compile_module()
106 return self._load_library()
107
108 def get_module_name(self):
109 basename = os.path.basename(self.modulefilename)
110 # kill both the .so extension and the other .'s, as introduced
111 # by Python 3: 'basename.cpython-33m.so'
112 basename = basename.split('.', 1)[0]
113 # and the _d added in Python 2 debug builds --- but try to be
114 # conservative and not kill a legitimate _d
115 if basename.endswith('_d') and hasattr(sys, 'gettotalrefcount'):
116 basename = basename[:-2]
117 return basename
118
119 def get_extension(self):
120 if not self._has_source:
121 with self.ffi._lock:
122 if not self._has_source:
123 self._write_source()
124 sourcename = ffiplatform.maybe_relative_path(self.sourcefilename)
125 modname = self.get_module_name()
126 return ffiplatform.get_extension(sourcename, modname, **self.kwds)
127
128 def generates_python_module(self):
129 return self._vengine._gen_python_module
130
131 def make_relative_to(self, kwds, relative_to):
132 if relative_to and os.path.dirname(relative_to):
133 dirname = os.path.dirname(relative_to)
134 kwds = kwds.copy()
135 for key in ffiplatform.LIST_OF_FILE_NAMES:
136 if key in kwds:
137 lst = kwds[key]
138 if not isinstance(lst, (list, tuple)):
139 raise TypeError("keyword '%s' should be a list or tuple"
140 % (key,))
141 lst = [os.path.join(dirname, fn) for fn in lst]
142 kwds[key] = lst
143 return kwds
144
145 # ----------
146
147 def _locate_module(self):
148 if not os.path.isfile(self.modulefilename):
149 if self.ext_package:
150 try:
151 pkg = __import__(self.ext_package, None, None, ['__doc__'])
152 except ImportError:
153 return # cannot import the package itself, give up
154 # (e.g. it might be called differently before installation)
155 path = pkg.__path__
156 else:
157 path = None
158 filename = self._vengine.find_module(self.get_module_name(), path,
159 _get_so_suffixes())
160 if filename is None:
161 return
162 self.modulefilename = filename
163 self._vengine.collect_types()
164 self._has_module = True
165
166 def _write_source_to(self, file):
167 self._vengine._f = file
168 try:
169 self._vengine.write_source_to_f()
170 finally:
171 del self._vengine._f
172
173 def _write_source(self, file=None):
174 if file is not None:
175 self._write_source_to(file)
176 else:
177 # Write our source file to an in memory file.
178 f = NativeIO()
179 self._write_source_to(f)
180 source_data = f.getvalue()
181
182 # Determine if this matches the current file
183 if os.path.exists(self.sourcefilename):
184 with open(self.sourcefilename, "r") as fp:
185 needs_written = not (fp.read() == source_data)
186 else:
187 needs_written = True
188
189 # Actually write the file out if it doesn't match
190 if needs_written:
191 _ensure_dir(self.sourcefilename)
192 with open(self.sourcefilename, "w") as fp:
193 fp.write(source_data)
194
195 # Set this flag
196 self._has_source = True
197
198 def _compile_module(self):
199 # compile this C source
200 # Note: compilation will create artifacts in tmpdir + sourcefilename
201 # This can exceed the windows MAXPATH quite easily. To make it shorter,
202 # cd into tmpdir and make the sourcefilename relative to tmdir
203 tmpdir = os.path.dirname(self.sourcefilename)
204 olddir = os.getcwd()
205 os.chdir(tmpdir)
206 self.sourcefilename_orig = self.sourcefilename
207 try:
208 self.sourcefilename = os.path.relpath(self.sourcefilename)
209 output_rel_filename = ffiplatform.compile(tmpdir, self.get_extension())
210 outputfilename = os.path.join(tmpdir, output_rel_filename)
211 finally:
212 os.chdir(olddir)
213 self.sourcefilename = self.sourcefilename_orig
214 try:
215 same = ffiplatform.samefile(outputfilename, self.modulefilename)
216 except OSError:
217 same = False
218 if not same:
219 _ensure_dir(self.modulefilename)
220 shutil.move(outputfilename, self.modulefilename)
221 self._has_module = True
222
223 def _load_library(self):
224 assert self._has_module
225 if self.flags is not None:
226 return self._vengine.load_library(self.flags)
227 else:
228 return self._vengine.load_library()
229
230 local = threading.local()
231 # ____________________________________________________________
232
233 local._FORCE_GENERIC_ENGINE = False # for tests
234
235 def _locate_engine_class(ffi, force_generic_engine):
236 if local._FORCE_GENERIC_ENGINE:
237 force_generic_engine = True
238 if not force_generic_engine:
239 if '__pypy__' in sys.builtin_module_names:
240 force_generic_engine = True
241 else:
242 try:
243 import _cffi_backend
244 except ImportError:
245 _cffi_backend = '?'
246 if ffi._backend is not _cffi_backend:
247 force_generic_engine = True
248 if force_generic_engine:
249 from . import vengine_gen
250 return vengine_gen.VGenericEngine
251 else:
252 from . import vengine_cpy
253 return vengine_cpy.VCPythonEngine
254
255 # ____________________________________________________________
256
257 local._TMPDIR = None
258
259 def _caller_dir_pycache():
260 if local._TMPDIR:
261 return local._TMPDIR
262 result = os.environ.get('CFFI_TMPDIR')
263 if result:
264 return result
265 filename = sys._getframe(2).f_code.co_filename
266 return os.path.abspath(os.path.join(os.path.dirname(filename),
267 '__pycache__'))
268
269 def set_tmpdir(dirname):
270 """Set the temporary directory to use instead of __pycache__."""
271 local._TMPDIR = dirname
272
273 def cleanup_tmpdir(tmpdir=None, keep_so=False):
274 """Clean up the temporary directory by removing all files in it
275 called `_cffi_*.{c,so}` as well as the `build` subdirectory."""
276 tmpdir = tmpdir or _caller_dir_pycache()
277 try:
278 filelist = os.listdir(tmpdir)
279 except OSError:
280 return
281 if keep_so:
282 suffix = '.c' # only remove .c files
283 else:
284 suffix = _get_so_suffixes()[0].lower()
285 for fn in filelist:
286 if fn.lower().startswith('_cffi_') and (
287 fn.lower().endswith(suffix) or fn.lower().endswith('.c')):
288 try:
289 os.unlink(os.path.join(tmpdir, fn))
290 except OSError:
291 pass
292 clean_dir = [os.path.join(tmpdir, 'build')]
293 for dir in clean_dir:
294 try:
295 for fn in os.listdir(dir):
296 fn = os.path.join(dir, fn)
297 if os.path.isdir(fn):
298 clean_dir.append(fn)
299 else:
300 os.unlink(fn)
301 except OSError:
302 pass
303
304 def _get_so_suffixes():
305 suffixes = _extension_suffixes()
306 if not suffixes:
307 # bah, no C_EXTENSION available. Occurs on pypy without cpyext
308 if sys.platform == 'win32':
309 suffixes = [".pyd"]
310 else:
311 suffixes = [".so"]
312
313 return suffixes
314
315 def _ensure_dir(filename):
316 dirname = os.path.dirname(filename)
317 if dirname and not os.path.isdir(dirname):
318 os.makedirs(dirname)