*.c: Introduce a new input conversion for binary strings.
[pyke] / pyke.c
1 /* -*-c-*-
2 *
3 * Pyke: the Python Kit for Extensions
4 *
5 * (c) 2019 Straylight/Edgeware
6 */
7
8 /*----- Licensing notice --------------------------------------------------*
9 *
10 * This file is part of Pyke: the Python Kit for Extensions.
11 *
12 * Pyke is free software: you can redistribute it and/or modify it under
13 * the terms of the GNU General Public License as published by the Free
14 * Software Foundation; either version 2 of the License, or (at your
15 * option) any later version.
16 *
17 * Pyke is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 * for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with Pyke. If not, write to the Free Software Foundation, Inc.,
24 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25 */
26
27 /*----- Header files ------------------------------------------------------*/
28
29 #include "pyke.h"
30
31 /*----- External variables ------------------------------------------------*/
32
33 PyObject *modname;
34 PyObject *home_module;
35
36 /*----- Conversions -------------------------------------------------------*/
37
38 PyObject *getulong(unsigned long w)
39 {
40 if (w <= LONG_MAX) return (PyInt_FromLong(w));
41 else return (PyLong_FromUnsignedLong(w));
42 }
43
44 PyObject *getbool(int b)
45 { if (b) RETURN_TRUE; else RETURN_FALSE; }
46
47 int convulong(PyObject *o, void *pp)
48 {
49 long i;
50 unsigned long *p = pp;
51 PyObject *t;
52
53 if (!o) VALERR("can't delete");
54 if (PyInt_Check(o)) {
55 i = PyInt_AS_LONG(o);
56 if (i < 0) VALERR("must be nonnegative");
57 *p = i;
58 } else {
59 if ((t = PyNumber_Long(o)) == 0) goto end;
60 *p = PyLong_AsUnsignedLong(t);
61 Py_DECREF(t);
62 if (PyErr_Occurred()) goto end;
63 }
64 return (1);
65 end:
66 return (0);
67 }
68
69 int convuint(PyObject *o, void *pp)
70 {
71 unsigned long u;
72 unsigned *p = pp;
73
74 if (!convulong(o, &u)) goto end;
75 if (u > UINT_MAX) VALERR("out of range");
76 *p = u;
77 return (1);
78 end:
79 return (0);
80 }
81
82 int convszt(PyObject *o, void *pp)
83 {
84 unsigned long u;
85 size_t *p = pp;
86
87 if (!convulong(o, &u)) goto end;
88 if (u > ~(size_t)0) VALERR("out of range");
89 *p = u;
90 return (1);
91 end:
92 return (0);
93 }
94
95 int convbool(PyObject *o, void *pp)
96 {
97 if (!o) VALERR("can't delete");
98 *(int *)pp = PyObject_IsTrue(o);
99 return (1);
100 end:
101 return (0);
102 }
103
104 int convbin(PyObject *o, void *pp)
105 {
106 struct bin *r = pp;
107
108 if (PyString_Check(o)) {
109 r->p = PyString_AS_STRING(o);
110 r->sz = PyString_GET_SIZE(o);
111 return (1);
112 }
113 if (PyUnicode_Check(o)) {
114 o = _PyUnicode_AsDefaultEncodedString(o, 0);
115 if (!o) return (0);
116 r->p = PyString_AS_STRING(o);
117 r->sz = PyString_GET_SIZE(o);
118 return (1);
119 }
120 return (PyObject_AsReadBuffer(o, &r->p, &r->sz) ? 0 : 1);
121 }
122
123 /*----- Miscellaneous utilities -------------------------------------------*/
124
125 PyObject *abstract_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
126 {
127 PyErr_SetString(PyExc_TypeError, "can't instantiate this class");
128 return (0);
129 }
130
131 /*----- Saving and restoring exceptions ----------------------------------*/
132
133 void report_lost_exception_v(struct excinfo *exc,
134 const char *why, va_list ap)
135 {
136 PyObject *hookfn = 0;
137 PyObject *whyobj = 0;
138 PyObject *obj = 0;
139
140 /* Make sure we start out without a pending exception, or this will get
141 * really confusing.
142 */
143 assert(!PyErr_Occurred());
144
145 /* Format the explanation. */
146 if (why) whyobj = PyString_FromFormatV(why, ap);
147 else { whyobj = Py_None; Py_INCREF(whyobj); }
148
149 /* Find our home module's `lostexchook' function. This won't work if
150 * there's no module, or the function isn't defined, or it's `None'.
151 */
152 if (!home_module) goto sys;
153 hookfn = PyObject_GetAttrString(home_module, "lostexchook");
154 if (hookfn == Py_None) goto sys;
155 else if (hookfn) ;
156 else if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto ouch;
157 else { PyErr_Clear(); goto sys; }
158
159 /* Call the hook function. */
160 obj = PyObject_CallFunction(hookfn, "(OOOO)",
161 whyobj, exc->ty, exc->val, exc->tb);
162 if (!obj) goto ouch;
163 goto end;
164
165 /* Something went wrong reporting the problem. */
166 ouch:
167 PySys_WriteStderr("\n!!! FAILURE REPORTING LOST EXCEPTION\n");
168 PyErr_Print();
169 /* drop through... */
170
171 /* There was no hook, so try to do something sensible using
172 * `sys.excepthook'.
173 */
174 sys:
175 PySys_WriteStderr("\n!!! LOST EXCEPTION: %s\n",
176 PyString_AS_STRING(whyobj));
177 RESTORE_EXCINFO(exc);
178 PyErr_Print();
179 /* drop through... */
180
181 /* Clean up afterwards. */
182 end:
183 Py_XDECREF(hookfn);
184 Py_XDECREF(whyobj);
185 Py_XDECREF(obj);
186 }
187
188 void report_lost_exception(struct excinfo *exc, const char *why, ...)
189 {
190 va_list ap;
191
192 va_start(ap, why);
193 report_lost_exception_v(exc, why, ap);
194 va_end(ap);
195 }
196
197 void stash_exception(struct excinfo *exc, const char *why, ...)
198 {
199 va_list ap;
200 struct excinfo stash;
201
202 if (!exc->ty)
203 STASH_EXCINFO(exc);
204 else {
205 va_start(ap, why);
206 STASH_EXCINFO(&stash);
207 report_lost_exception_v(&stash, why, ap);
208 va_end(ap);
209 }
210 }
211
212 void restore_exception(struct excinfo *exc, const char *why, ...)
213 {
214 va_list ap;
215 struct excinfo stash;
216
217 if (!PyErr_Occurred())
218 RESTORE_EXCINFO(exc);
219 else {
220 va_start(ap, why);
221 STASH_EXCINFO(&stash);
222 report_lost_exception_v(exc, why, ap);
223 RESTORE_EXCINFO(&stash);
224 va_end(ap);
225 }
226 }
227
228 /*----- Type definitions --------------------------------------------------*/
229
230 static const PyTypeObject emptytype = { 0 };
231
232 void *newtype(PyTypeObject *metaty,
233 const PyTypeObject *skel,
234 const char *name)
235 {
236 PyHeapTypeObject *ty =
237 (PyHeapTypeObject *)_PyObject_GC_Malloc(_PyObject_VAR_SIZE(metaty, 0));
238 if (!skel) skel = &emptytype;
239 memcpy(ty, skel, sizeof(*skel));
240 #define COPY(blah) do { \
241 if (ty->ht_type.tp_as_##blah) { \
242 memcpy(&ty->as_##blah, \
243 ty->ht_type.tp_as_##blah, \
244 sizeof(ty->as_##blah)); \
245 ty->ht_type.tp_as_##blah = &ty->as_##blah; \
246 } \
247 } while (0)
248 COPY(number);
249 COPY(sequence);
250 COPY(mapping);
251 COPY(buffer);
252 #undef COPY
253 if (name)
254 ty->ht_name = PyString_FromString(name);
255 else if (ty->ht_type.tp_name)
256 ty->ht_name = PyString_FromString(ty->ht_type.tp_name);
257 if (ty->ht_name)
258 ty->ht_type.tp_name = PyString_AS_STRING(ty->ht_name);
259 ty->ht_slots = 0;
260 (void)PyObject_INIT(&ty->ht_type, metaty);
261 Py_INCREF(metaty);
262 return (ty);
263 }
264
265 void typeready(PyTypeObject *ty)
266 {
267 PyType_Ready(ty);
268 PyDict_SetItemString(ty->tp_dict, "__module__", modname);
269 }
270
271 PyTypeObject *inittype(const PyTypeObject *tyskel,
272 PyTypeObject *base, PyTypeObject *meta)
273 {
274 PyTypeObject *ty = newtype(meta, tyskel, 0);
275 if (base) { ty->tp_base = base; Py_INCREF(base); }
276 ty->tp_flags |= Py_TPFLAGS_HEAPTYPE;
277 typeready(ty);
278 return (ty);
279 }
280
281 /*----- Populating modules ------------------------------------------------*/
282
283 PyObject *mkexc(PyObject *mod, PyObject *base,
284 const char *name, const PyMethodDef *mm)
285 {
286 PyObject *nameobj = 0;
287 PyObject *dict = 0;
288 PyObject *exc = 0;
289 PyObject *func = 0;
290 PyObject *meth = 0;
291
292 if ((dict = PyDict_New()) == 0) goto fail;
293
294 if (mm) {
295 while (mm->ml_name) {
296 if ((func = PyCFunction_NewEx((/*unconst*/ PyMethodDef *)mm,
297 0, mod)) == 0 ||
298 (meth = PyMethod_New(func, 0, exc)) == 0 ||
299 PyDict_SetItemString(dict, mm->ml_name, meth))
300 goto fail;
301 Py_DECREF(func); func = 0;
302 Py_DECREF(meth); meth = 0;
303 mm++;
304 }
305 }
306
307 if ((nameobj = PyString_FromFormat("%s.%s",
308 PyModule_GetName(mod),
309 name)) == 0 ||
310 (exc = PyErr_NewException(PyString_AS_STRING(nameobj),
311 base, dict)) == 0)
312 goto fail;
313
314 done:
315 Py_XDECREF(nameobj);
316 Py_XDECREF(dict);
317 return (exc);
318
319 fail:
320 Py_XDECREF(exc);
321 Py_XDECREF(func);
322 Py_XDECREF(meth);
323 exc = 0;
324 goto done;
325 }
326
327 void setconstants(PyObject *mod, const struct nameval *c)
328 {
329 PyObject *x;
330 unsigned long u;
331
332 while (c->name) {
333 u = c->value;
334 if (u <= LONG_MAX) x = PyInt_FromLong(u);
335 else if (c->f&CF_SIGNED) x = PyInt_FromLong(-1 - (long)(ULONG_MAX - u));
336 else x = PyLong_FromUnsignedLong(u);
337 PyModule_AddObject(mod, (/*unconst*/ char *)c->name, x);
338 c++;
339 }
340 }
341
342 /*----- Submodules --------------------------------------------------------*/
343
344 static PyMethodDef *global_methods;
345 static size_t nmethods, methodsz;
346
347 void addmethods(const PyMethodDef *m)
348 {
349 size_t n, want, newsz;
350
351 for (n = 0; m[n].ml_name; n++);
352 want = nmethods + n + 1;
353 if (want > methodsz) {
354 newsz = methodsz ? 2*methodsz : 16;
355 while (want > newsz) newsz *= 2;
356 if (!global_methods)
357 global_methods = PyObject_Malloc(newsz*sizeof(PyMethodDef));
358 else
359 global_methods = PyObject_Realloc(global_methods,
360 newsz*sizeof(PyMethodDef));
361 assert(global_methods);
362 methodsz = newsz;
363 }
364 memcpy(global_methods + nmethods, m, n*sizeof(PyMethodDef));
365 nmethods += n;
366 global_methods[nmethods].ml_name = 0;
367 }
368
369 PyMethodDef *donemethods(void) { return (global_methods); }
370
371 /*----- Low-level Python interface ----------------------------------------*/
372
373 static PyObject *meth__set_home_module(PyObject *me, PyObject *arg)
374 {
375 PyObject *mod;
376
377 if (!PyArg_ParseTuple(arg, "O!:_set_home_module", &PyModule_Type, &mod))
378 return (0);
379 Py_XDECREF(home_module); home_module = mod; Py_INCREF(home_module);
380 RETURN_NONE;
381 }
382
383 static const PyMethodDef methods[] = {
384 #define METHNAME(func) meth_##func
385 METH (_set_home_module, "_set_home_module(MOD)")
386 #undef METHNAME
387 { 0 }
388 };
389
390 void pyke_core_pyinit(void) { addmethods(methods); }
391 void pyke_core_pyinsert(PyObject *mod) { ; }
392
393 /*----- That's all, folks -------------------------------------------------*/