chiark / gitweb /
*.c: Make all of the type-definition tables read-only.
[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 /*----- Miscellaneous utilities -------------------------------------------*/
105
106 PyObject *abstract_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
107 {
108   PyErr_SetString(PyExc_TypeError, "can't instantiate this class");
109   return (0);
110 }
111
112 /*----- Saving and restoring exceptions ----------------------------------*/
113
114 void report_lost_exception_v(struct excinfo *exc,
115                              const char *why, va_list ap)
116 {
117   PyObject *hookfn = 0;
118   PyObject *whyobj = 0;
119   PyObject *obj = 0;
120
121   /* Make sure we start out without a pending exception, or this will get
122    * really confusing.
123    */
124   assert(!PyErr_Occurred());
125
126   /* Format the explanation. */
127   if (why) whyobj = PyString_FromFormatV(why, ap);
128   else { whyobj = Py_None; Py_INCREF(whyobj); }
129
130   /* Find our home module's `lostexchook' function.  This won't work if
131    * there's no module, or the function isn't defined, or it's `None'.
132    */
133   if (!home_module) goto sys;
134   hookfn = PyObject_GetAttrString(home_module, "lostexchook");
135   if (hookfn == Py_None) goto sys;
136   else if (hookfn) ;
137   else if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto ouch;
138   else { PyErr_Clear(); goto sys; }
139
140   /* Call the hook function. */
141   obj = PyObject_CallFunction(hookfn, "(OOOO)",
142                               whyobj, exc->ty, exc->val, exc->tb);
143   if (!obj) goto ouch;
144   goto end;
145
146   /* Something went wrong reporting the problem. */
147 ouch:
148   PySys_WriteStderr("\n!!! FAILURE REPORTING LOST EXCEPTION\n");
149   PyErr_Print();
150   /* drop through... */
151
152   /* There was no hook, so try to do something sensible using
153    * `sys.excepthook'.
154    */
155 sys:
156   PySys_WriteStderr("\n!!! LOST EXCEPTION: %s\n",
157                     PyString_AS_STRING(whyobj));
158   RESTORE_EXCINFO(exc);
159   PyErr_Print();
160   /* drop through... */
161
162   /* Clean up afterwards. */
163 end:
164   Py_XDECREF(hookfn);
165   Py_XDECREF(whyobj);
166   Py_XDECREF(obj);
167 }
168
169 void report_lost_exception(struct excinfo *exc, const char *why, ...)
170 {
171   va_list ap;
172
173   va_start(ap, why);
174   report_lost_exception_v(exc, why, ap);
175   va_end(ap);
176 }
177
178 void stash_exception(struct excinfo *exc, const char *why, ...)
179 {
180   va_list ap;
181   struct excinfo stash;
182
183   if (!exc->ty)
184     STASH_EXCINFO(exc);
185   else {
186     va_start(ap, why);
187     STASH_EXCINFO(&stash);
188     report_lost_exception_v(&stash, why, ap);
189     va_end(ap);
190   }
191 }
192
193 void restore_exception(struct excinfo *exc, const char *why, ...)
194 {
195   va_list ap;
196   struct excinfo stash;
197
198   if (!PyErr_Occurred())
199     RESTORE_EXCINFO(exc);
200   else {
201     va_start(ap, why);
202     STASH_EXCINFO(&stash);
203     report_lost_exception_v(exc, why, ap);
204     RESTORE_EXCINFO(&stash);
205     va_end(ap);
206   }
207 }
208
209 /*----- Type definitions --------------------------------------------------*/
210
211 static const PyTypeObject emptytype = { 0 };
212
213 void *newtype(PyTypeObject *metaty,
214               const PyTypeObject *skel,
215               const char *name)
216 {
217   PyHeapTypeObject *ty =
218     (PyHeapTypeObject *)_PyObject_GC_Malloc(_PyObject_VAR_SIZE(metaty, 0));
219   if (!skel) skel = &emptytype;
220   memcpy(ty, skel, sizeof(*skel));
221   if (ty->ht_type.tp_base) Py_INCREF(ty->ht_type.tp_base);
222 #define COPY(blah) do {                                                 \
223     if (ty->ht_type.tp_as_##blah) {                                     \
224       memcpy(&ty->as_##blah,                                            \
225              ty->ht_type.tp_as_##blah,                                  \
226              sizeof(ty->as_##blah));                                    \
227       ty->ht_type.tp_as_##blah = &ty->as_##blah;                        \
228     }                                                                   \
229   } while (0)
230   COPY(number);
231   COPY(sequence);
232   COPY(mapping);
233   COPY(buffer);
234 #undef COPY
235   if (name)
236     ty->ht_name = PyString_FromString(name);
237   else if (ty->ht_type.tp_name)
238     ty->ht_name = PyString_FromString(ty->ht_type.tp_name);
239   if (ty->ht_name)
240     ty->ht_type.tp_name = PyString_AS_STRING(ty->ht_name);
241   (void)PyObject_INIT(&ty->ht_type, metaty);
242   Py_INCREF(metaty);
243   return (ty);
244 }
245
246 void typeready(PyTypeObject *ty)
247 {
248   PyType_Ready(ty);
249   PyDict_SetItemString(ty->tp_dict, "__module__", modname);
250 }
251
252 PyTypeObject *inittype(PyTypeObject *tyskel, PyTypeObject *meta)
253 {
254   PyTypeObject *ty = newtype(meta, tyskel, 0);
255   ty->tp_flags |= Py_TPFLAGS_HEAPTYPE;
256   typeready(ty);
257   return (ty);
258 }
259
260 /*----- Populating modules ------------------------------------------------*/
261
262 PyObject *mkexc(PyObject *mod, PyObject *base,
263                 const char *name, const PyMethodDef *mm)
264 {
265   PyObject *nameobj = 0;
266   PyObject *dict = 0;
267   PyObject *exc = 0;
268   PyObject *func = 0;
269   PyObject *meth = 0;
270
271   if ((dict = PyDict_New()) == 0) goto fail;
272
273   if (mm) {
274     while (mm->ml_name) {
275       if ((func = PyCFunction_NewEx((/*unconst*/ PyMethodDef *)mm,
276                                     0, mod)) == 0 ||
277           (meth = PyMethod_New(func, 0, exc)) == 0 ||
278           PyDict_SetItemString(dict, mm->ml_name, meth))
279         goto fail;
280       Py_DECREF(func); func = 0;
281       Py_DECREF(meth); meth = 0;
282       mm++;
283     }
284   }
285
286   if ((nameobj = PyString_FromFormat("%s.%s",
287                                      PyModule_GetName(mod),
288                                      name)) == 0 ||
289       (exc = PyErr_NewException(PyString_AS_STRING(nameobj),
290                                 base, dict)) == 0)
291     goto fail;
292
293 done:
294   Py_XDECREF(nameobj);
295   Py_XDECREF(dict);
296   return (exc);
297
298 fail:
299   Py_XDECREF(exc);
300   Py_XDECREF(func);
301   Py_XDECREF(meth);
302   exc = 0;
303   goto done;
304 }
305
306 void setconstants(PyObject *mod, const struct nameval *c)
307 {
308   PyObject *x;
309   unsigned long u;
310
311   while (c->name) {
312     u = c->value;
313     if (u <= LONG_MAX) x = PyInt_FromLong(u);
314     else if (c->f&CF_SIGNED) x = PyInt_FromLong(-1 - (long)(ULONG_MAX - u));
315     else x = PyLong_FromUnsignedLong(u);
316     PyModule_AddObject(mod, (/*unconst*/ char *)c->name, x);
317     c++;
318   }
319 }
320
321 /*----- Submodules --------------------------------------------------------*/
322
323 static PyMethodDef *global_methods;
324 static size_t nmethods, methodsz;
325
326 void addmethods(const PyMethodDef *m)
327 {
328   size_t n, want, newsz;
329
330   for (n = 0; m[n].ml_name; n++);
331   want = nmethods + n + 1;
332   if (want > methodsz) {
333     newsz = methodsz ? 2*methodsz : 16;
334     while (want > newsz) newsz *= 2;
335     if (!global_methods)
336       global_methods = PyObject_Malloc(newsz*sizeof(PyMethodDef));
337     else
338       global_methods = PyObject_Realloc(global_methods,
339                                         newsz*sizeof(PyMethodDef));
340     assert(global_methods);
341     methodsz = newsz;
342   }
343   memcpy(global_methods + nmethods, m, n*sizeof(PyMethodDef));
344   nmethods += n;
345   global_methods[nmethods].ml_name = 0;
346 }
347
348 PyMethodDef *donemethods(void) { return (global_methods); }
349
350 /*----- Low-level Python interface ----------------------------------------*/
351
352 static PyObject *meth__set_home_module(PyObject *me, PyObject *arg)
353 {
354   PyObject *mod;
355
356   if (!PyArg_ParseTuple(arg, "O!:_set_home_module", &PyModule_Type, &mod))
357     return (0);
358   Py_XDECREF(home_module); home_module = mod; Py_INCREF(home_module);
359   RETURN_NONE;
360 }
361
362 static const PyMethodDef methods[] = {
363 #define METHNAME(func) meth_##func
364   METH  (_set_home_module, "_set_home_module(MOD)")
365 #undef METHNAME
366   { 0 }
367 };
368
369 void pyke_core_pyinit(void) { addmethods(methods); }
370 void pyke_core_pyinsert(PyObject *mod) { ; }
371
372 /*----- That's all, folks -------------------------------------------------*/