Debian Codegraph @

pypy/module/_hpy_universal/interp_hpy.py

raw symbols SCIP
1 from rpython.rtyper.lltypesystem import lltype, rffi
2 from rpython.rlib.rdynload import dlopen, dlsym, DLOpenError
3 from rpython.rlib.objectmodel import specialize
4 from rpython.rlib.rarithmetic import widen
5
6 from pypy.interpreter.gateway import unwrap_spec, interp2app
7 from pypy.interpreter.error import raise_import_error
8 from pypy.interpreter.error import oefmt, OperationError
9
10 from pypy.module._hpy_universal import llapi
11 from pypy.module._hpy_universal.state import State
12 from pypy.module._hpy_universal.apiset import API
13 from pypy.module._hpy_universal.interp_module import hpymod_create, hpymod_exec_def
14
15 # these imports have side effects, as they call @API.func()
16 from pypy.module._hpy_universal import (
17 interp_builder,
18 interp_bytes,
19 interp_call,
20 interp_capsule,
21 interp_contextvars,
22 interp_cpy_compat,
23 interp_dict,
24 interp_err,
25 interp_eval,
26 interp_field,
27 interp_float,
28 interp_import,
29 interp_list,
30 interp_long,
31 interp_module,
32 interp_number,
33 interp_object,
34 interp_slice,
35 interp_state,
36 interp_tracker,
37 interp_tuple,
38 interp_type,
39 interp_unicode,
40 )
41
42 # ~~~ Some info on the debug mode ~~~
43 # XXX REVIEW for 0.9
44 #
45 # The following is an explation of what happens when you load a module
46 #
47 # 1. someone calls _hpy_universal.load(..., mode=MODE_XXX)
48 #
49 # 2. load() calls get_context(mode) which returns a debug context
50 # and later calls HPyInitGlobalContext_foo(ctx) to set up a global
51 # context in the module
52 #
53 # 5. The net result is that depending on the value of mode at point (1), we
54 # call the underlying C function with either dctx or uctx.
55 #
56 # 6. Argument passing works in the same way: handles are created by calling
57 # self.handles.new, which in debug mode calls
58 # llapi.hpy_debug_open_handle. The same for the return value, which calls
59 # self.handles.consume which calls llapi.hpy_debug_close_handle.
60 #
61 # 7. We need to ensure that ALL python-to-C entry points use the correct
62 # HandleManager/ctx: so the same applies for W_ExtensionMethod and
63 # W_SlotWrapper.
64
65 def startup(space, w_mod):
66 """
67 Initialize _hpy_universal. This is called by moduledef.Module.__init__
68 """
69 from pypy.module._hpy_universal.interp_type import setup_hpy_storage
70 state = State.get(space)
71 state.setup(space)
72 setup_hpy_storage()
73
74 # do the following lines break test_ztranslation?
75 manager = state.get_handle_manager(llapi.MODE_UNIVERSAL)
76 hpydef_debug = llapi.HPyInit__debug()
77 w_debug_mod = hpymod_create(manager, "_debug", hpydef_debug)
78 hpymod_exec_def(manager, w_debug_mod, hpydef_debug)
79 w_mod.setdictvalue(space, '_debug', w_debug_mod)
80
81 hpydef_trace = llapi.HPyInit__trace()
82 w_trace_mod = hpymod_create(manager, "_trace", hpydef_trace)
83 hpymod_exec_def(manager, w_trace_mod, hpydef_trace)
84 w_mod.setdictvalue(space, '_trace', w_trace_mod)
85
86
87 def load_version():
88 # eval the content of _vendored/hpy/devel/version.py without importing it
89 version_py = llapi.BASE_DIR.join('version.py').read()
90 d = {}
91 exec(version_py, d)
92 return d['__version__'], d['__git_revision__']
93 HPY_VERSION, HPY_GIT_REV = load_version()
94
95 @unwrap_spec(name='text', path='fsencode', debug=bool, mode=int)
96 def descr_load(space, name, path, w_spec, debug=False, mode=-1):
97 hmode = llapi.MODE_DEBUG if debug else llapi.MODE_UNIVERSAL
98 if mode > 0:
99 hmode = mode
100 w_mod = do_load(space, name, path, hmode)
101 space.setattr(w_mod, space.newtext("spec"), w_spec)
102 return w_mod
103
104 @unwrap_spec(ext_name="text", path="fsencode")
105 def descr__load_bootstrap(space, w_name, ext_name, w_package, path, w_loader, w_spec, w_env):
106 """Internal function intended to be used by the stub loader. This function
107 will honor env var 'HPY' and correctly set the attributes of the module.
108 """
109 name = space.text_w(w_name)
110 w_file = space.newtext(ext_name)
111
112 hmode = get_hpy_mode_from_environ(space, name, w_env);
113 w_mod = do_load(space, name, path, hmode)
114 space.setattr(w_mod, space.newtext("__name__"), w_name)
115 space.setattr(w_mod, space.newtext("__file__"), w_file)
116 space.setattr(w_mod, space.newtext("__loader__"), w_loader)
117 space.setattr(w_mod, space.newtext("__package__"), w_package)
118 space.setattr(w_spec, space.newtext("origin"), space.newtext(path))
119 space.setattr(w_mod, space.newtext("__spec__"), w_spec)
120 return w_mod
121
122 def get_mode_from_value(value):
123 if value.startswith("universal"):
124 return llapi.MODE_UNIVERSAL
125 elif value.startswith("debug"):
126 return llapi.MODE_DEBUG
127 elif value.startswith("trace"):
128 return llapi.MODE_TRACE
129 return llapi.MODE_INVALID
130
131 def get_hpy_mode_from_environ(space, name, w_env):
132 """w_env is os.environ. w_env[HPY] is HPY_MODE
133 HPY_MODE := MODE | (MODULE_NAME ':' MODE { ',' MODULE_NAME ':' MODE })
134 MODULE_NAME := IDENTIFIER
135 MODE := 'debug' | 'trace' | 'universal'
136 """
137 try:
138 w_HPY = space.newtext("HPY")
139 try:
140 w_value = space.getitem(w_env, w_HPY)
141 except OperationError:
142 return llapi.MODE_UNIVERSAL
143 value = space.text_w(w_value)
144 res = llapi.MODE_INVALID
145 if ":" not in value:
146 res = get_mode_from_value(value)
147 pieces = value.split(",")
148 for p in pieces:
149 if ":" in p:
150 mod_name, mode = p.split(":")
151 if mod_name == name:
152 res = get_mode_from_value(mode)
153 if res == llapi.MODE_INVALID:
154 raise oefmt(space.w_ValueError, "invalid HPY env value: %s", value)
155 return res
156 except Exception:
157 return llapi.MODE_INVALID
158
159
160 def validate_abi_tag(space, shortname, soname, req_major_version, req_minor_version):
161 i = soname.find(".hpy")
162 if i > 0:
163 i += len(".hpy")
164 if soname[i] >= "0" and soname[i] <= "9":
165 # it is a number w/o sign and whitespace. In C we could use atio,
166 # but here we need to scan for the end of the digits
167 abi_tag = 0
168 while (soname[i] >= "0" and soname[i] <= "9"):
169 abi_tag *= 10
170 abi_tag += int(soname[i])
171 i += 1
172 if (i >= len(soname)):
173 break
174 if abi_tag == req_major_version:
175 return True
176 raise oefmt(space.w_RuntimeError,
177 "HPy extension module '%s' at path '%s': mismatch between the "
178 "HPy ABI tag encoded in the filename and the major version requested "
179 "by the HPy extension itself. Major version tag parsed from "
180 "filename: %d. Requested version: %d.%d.", shortname,
181 soname, abi_tag, req_major_version, req_minor_version)
182 raise oefmt(space.w_RuntimeError,
183 "HPy extension module '%s' at path '%s': could not find "
184 "HPy ABI tag encoded in the filename. The extension claims to be compiled with "
185 "HPy ABI version: %d.%d.", shortname, soname,
186 req_major_version, req_minor_version)
187
188 def get_handle_manager(space, mode):
189 # So the result can be pre-built
190 state = State.get(space)
191 if mode == llapi.MODE_DEBUG:
192 return state.get_handle_manager(llapi.MODE_DEBUG)
193 elif mode == llapi.MODE_UNIVERSAL:
194 return state.get_handle_manager(llapi.MODE_UNIVERSAL)
195 elif mode == llapi.MODE_TRACE:
196 return state.get_handle_manager(llapi.MODE_TRACE)
197 else:
198 return state.get_handle_manager(llapi.MODE_INVALID)
199
200
201 def do_load(space, name, soname, mode):
202 """This is hpy/hpy/universal/src/hpymodule.c:do_load
203 """
204 if space.config.objspace.hpy_cpyext_API:
205 # Ensure cpyext is initialised, since the extension might call cpyext
206 # functions
207 space.getbuiltinmodule('cpyext')
208
209 try:
210 lib = dlopen(soname, space.sys.dlopenflags)
211 except DLOpenError as e:
212 w_path = space.newfilename(soname)
213 raise raise_import_error(space,
214 space.newfilename(e.msg), space.newtext(name), w_path)
215
216 shortname = name.split('.')[-1]
217 minor_version_symbol_name = "get_required_hpy_minor_version_%s" % shortname
218 major_version_symbol_name = "get_required_hpy_major_version_%s" % shortname
219 try:
220 minor_version_ptr = dlsym(lib, minor_version_symbol_name)
221 major_version_ptr = dlsym(lib, major_version_symbol_name)
222 except KeyError:
223 raise oefmt(space.w_RuntimeError,
224 ("Error during loading of the HPy extension module at path "
225 "'%s'. Cannot locate the required minimal HPy versions as symbols "
226 "'%s' and `%s`. "), soname, minor_version_symbol_name,
227 major_version_symbol_name)
228 vgfp = llapi.VersionGetterFuncPtr
229 required_minor_version = widen(rffi.cast(vgfp, minor_version_ptr)())
230 required_major_version = widen(rffi.cast(vgfp, major_version_ptr)())
231 if (required_major_version != llapi.HPY_ABI_VERSION or
232 required_minor_version > llapi.HPY_ABI_VERSION_MINOR):
233 # For now, we have only one major version, but in the future at this
234 # point we would decide which HPyContext to create
235 raise oefmt(space.w_RuntimeError,
236 ("HPy extension module '%s' requires unsupported version of the HPy "
237 "runtime. Requested version: %d.%d. Current HPy version: %d.%d."),
238 shortname, required_major_version, required_minor_version,
239 llapi.HPY_ABI_VERSION, llapi.HPY_ABI_VERSION_MINOR)
240
241 validate_abi_tag(space, shortname, soname, required_major_version, required_minor_version)
242 manager = get_handle_manager(space, mode)
243
244 init_ctx_name = "HPyInitGlobalContext_" + shortname
245 try:
246 initptr = dlsym(lib, init_ctx_name)
247 except KeyError:
248 msg = b"function %s not found in library %s" % (
249 init_ctx_name, space.utf8_w(space.newfilename(soname)))
250 w_path = space.newfilename(soname)
251 raise raise_import_error(
252 space, space.newtext(msg), space.newtext(name), w_path)
253
254 # Set up global trampoline ctx
255 if mode == llapi.MODE_DEBUG:
256 ctx = manager.ctx
257 elif mode == llapi.MODE_UNIVERSAL:
258 ctx = manager.ctx
259 elif mode == llapi.MODE_TRACE:
260 ctx = llapi.hpy_trace_get_ctx(manager.u_handles.ctx)
261 else:
262 # Cannot happen
263 ctx = llapi.cts.cast("HPyContext *", 0)
264 rffi.cast(llapi.InitContextFuncPtr, initptr)(ctx)
265
266 init_name = 'HPyInit_' + shortname
267 try:
268 initptr = dlsym(lib, init_name)
269 except KeyError:
270 msg = b"function %s not found in library %s" % (
271 init_name, space.utf8_w(space.newfilename(soname)))
272 w_path = space.newfilename(soname)
273 raise raise_import_error(
274 space, space.newtext(msg), space.newtext(name), w_path)
275
276 hpydef = rffi.cast(llapi.InitFuncPtr, initptr)()
277 if not hpydef:
278 raise oefmt(space.w_RuntimeError,
279 ("Error during loading of the HPy extension module at "
280 "path '%s'. Function '%s' returned NULL."), soname, init_name);
281
282 # specialize hpymod_create and hpymod_exec_def, which requires
283 # a constant 'manager'
284 state = State.get(space)
285 if mode == llapi.MODE_DEBUG:
286 manager = state.get_handle_manager(llapi.MODE_DEBUG)
287 w_mod = hpymod_create(manager, name, hpydef)
288 # find and call functions in the HPy_mod_exec slot
289 hpymod_exec_def(manager, w_mod, hpydef)
290 elif mode == llapi.MODE_UNIVERSAL:
291 manager = state.get_handle_manager(llapi.MODE_UNIVERSAL)
292 w_mod = hpymod_create(manager, name, hpydef)
293 # find and call functions in the HPy_mod_exec slot
294 hpymod_exec_def(manager, w_mod, hpydef)
295 elif mode == llapi.MODE_TRACE:
296 manager = state.get_handle_manager(llapi.MODE_TRACE)
297 w_mod = hpymod_create(manager, name, hpydef)
298 # find and call functions in the HPy_mod_exec slot
299 hpymod_exec_def(manager, w_mod, hpydef)
300 else:
301 # Raises an error, but pretend it doesn't for translation
302 manager = state.get_handle_manager(llapi.MODE_INVALID)
303 w_mod = hpymod_create(manager, name, hpydef)
304 return w_mod
305
306 def descr_get_version(space):
307 w_ver = space.newtext(HPY_VERSION)
308 w_git_rev = space.newtext(HPY_GIT_REV)
309 return space.newtuple([w_ver, w_git_rev])
310
311 @API.func("HPy HPy_Dup(HPyContext *ctx, HPy h)")
312 def HPy_Dup(space, handles, ctx, h):
313 if not h:
314 return h
315 return handles.dup(h)
316
317 @API.func("void HPy_Close(HPyContext *ctx, HPy h)")
318 def HPy_Close(space, handles, ctx, h):
319 if h:
320 handles.close(h)