pyke/pyke-mLib.c: Raise `OverflowError' on out-of-range inputs.
[pyke] / pyke.c
CommitLineData
c1756f78
MW
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
33PyObject *modname;
34PyObject *home_module;
35
36/*----- Conversions -------------------------------------------------------*/
37
38PyObject *getulong(unsigned long w)
39{
40 if (w <= LONG_MAX) return (PyInt_FromLong(w));
41 else return (PyLong_FromUnsignedLong(w));
42}
43
44PyObject *getbool(int b)
45 { if (b) RETURN_TRUE; else RETURN_FALSE; }
46
47int convulong(PyObject *o, void *pp)
48{
c1756f78
MW
49 unsigned long *p = pp;
50 PyObject *t;
51
52 if (!o) VALERR("can't delete");
c80de12d 53#ifdef PY2
c1756f78 54 if (PyInt_Check(o)) {
83a72c0d 55 long i = PyInt_AS_LONG(o);
c1756f78
MW
56 if (i < 0) VALERR("must be nonnegative");
57 *p = i;
83a72c0d 58 } else
c80de12d 59#endif
83a72c0d 60 {
c1756f78
MW
61 if ((t = PyNumber_Long(o)) == 0) goto end;
62 *p = PyLong_AsUnsignedLong(t);
63 Py_DECREF(t);
64 if (PyErr_Occurred()) goto end;
65 }
66 return (1);
67end:
68 return (0);
69}
70
71int convuint(PyObject *o, void *pp)
72{
73 unsigned long u;
74 unsigned *p = pp;
75
76 if (!convulong(o, &u)) goto end;
77 if (u > UINT_MAX) VALERR("out of range");
78 *p = u;
79 return (1);
80end:
81 return (0);
82}
83
84int convszt(PyObject *o, void *pp)
85{
86 unsigned long u;
87 size_t *p = pp;
88
89 if (!convulong(o, &u)) goto end;
90 if (u > ~(size_t)0) VALERR("out of range");
91 *p = u;
92 return (1);
93end:
94 return (0);
95}
96
97int convbool(PyObject *o, void *pp)
98{
99 if (!o) VALERR("can't delete");
100 *(int *)pp = PyObject_IsTrue(o);
101 return (1);
102end:
103 return (0);
104}
105
7e18a150
MW
106int convbin(PyObject *o, void *pp)
107{
108 struct bin *r = pp;
109
e0a7dece
MW
110 if (BIN_CHECK(o)) {
111 r->p = BIN_PTR(o);
112 r->sz = BIN_LEN(o);
7e18a150
MW
113 return (1);
114 }
c80de12d 115#ifdef PY2
7e18a150
MW
116 if (PyUnicode_Check(o)) {
117 o = _PyUnicode_AsDefaultEncodedString(o, 0);
118 if (!o) return (0);
119 r->p = PyString_AS_STRING(o);
120 r->sz = PyString_GET_SIZE(o);
121 return (1);
122 }
c80de12d 123#endif
7e18a150
MW
124 return (PyObject_AsReadBuffer(o, &r->p, &r->sz) ? 0 : 1);
125}
126
c1756f78
MW
127/*----- Miscellaneous utilities -------------------------------------------*/
128
129PyObject *abstract_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
130{
131 PyErr_SetString(PyExc_TypeError, "can't instantiate this class");
132 return (0);
133}
134
1c0e9c88
MW
135PyObject *enrich_compare(int op, int cmp)
136{
137 int r = -1;
138
139 switch (op) {
140 case Py_LT: r = cmp < 0; break;
141 case Py_LE: r = cmp <= 0; break;
142 case Py_EQ: r = cmp == 0; break;
143 case Py_NE: r = cmp != 0; break;
144 case Py_GE: r = cmp >= 0; break;
145 case Py_GT: r = cmp > 0; break;
146 default: assert(0);
147 }
148 return (getbool(r));
149}
150
c1756f78
MW
151/*----- Saving and restoring exceptions ----------------------------------*/
152
153void report_lost_exception_v(struct excinfo *exc,
154 const char *why, va_list ap)
155{
156 PyObject *hookfn = 0;
157 PyObject *whyobj = 0;
158 PyObject *obj = 0;
159
160 /* Make sure we start out without a pending exception, or this will get
161 * really confusing.
162 */
163 assert(!PyErr_Occurred());
164
165 /* Format the explanation. */
e0a7dece 166 if (why) whyobj = TEXT_VFORMAT(why, ap);
c1756f78
MW
167 else { whyobj = Py_None; Py_INCREF(whyobj); }
168
169 /* Find our home module's `lostexchook' function. This won't work if
170 * there's no module, or the function isn't defined, or it's `None'.
171 */
172 if (!home_module) goto sys;
173 hookfn = PyObject_GetAttrString(home_module, "lostexchook");
174 if (hookfn == Py_None) goto sys;
175 else if (hookfn) ;
176 else if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto ouch;
177 else { PyErr_Clear(); goto sys; }
178
179 /* Call the hook function. */
180 obj = PyObject_CallFunction(hookfn, "(OOOO)",
181 whyobj, exc->ty, exc->val, exc->tb);
182 if (!obj) goto ouch;
183 goto end;
184
185 /* Something went wrong reporting the problem. */
186ouch:
187 PySys_WriteStderr("\n!!! FAILURE REPORTING LOST EXCEPTION\n");
188 PyErr_Print();
189 /* drop through... */
190
191 /* There was no hook, so try to do something sensible using
192 * `sys.excepthook'.
193 */
194sys:
e0a7dece 195 PySys_WriteStderr("\n!!! LOST EXCEPTION: %s\n", TEXT_PTR(whyobj));
c1756f78
MW
196 RESTORE_EXCINFO(exc);
197 PyErr_Print();
198 /* drop through... */
199
200 /* Clean up afterwards. */
201end:
202 Py_XDECREF(hookfn);
203 Py_XDECREF(whyobj);
204 Py_XDECREF(obj);
205}
206
207void report_lost_exception(struct excinfo *exc, const char *why, ...)
208{
209 va_list ap;
210
211 va_start(ap, why);
212 report_lost_exception_v(exc, why, ap);
213 va_end(ap);
214}
215
216void stash_exception(struct excinfo *exc, const char *why, ...)
217{
218 va_list ap;
219 struct excinfo stash;
220
221 if (!exc->ty)
222 STASH_EXCINFO(exc);
223 else {
224 va_start(ap, why);
225 STASH_EXCINFO(&stash);
226 report_lost_exception_v(&stash, why, ap);
227 va_end(ap);
228 }
229}
230
231void restore_exception(struct excinfo *exc, const char *why, ...)
232{
233 va_list ap;
234 struct excinfo stash;
235
236 if (!PyErr_Occurred())
237 RESTORE_EXCINFO(exc);
238 else {
239 va_start(ap, why);
240 STASH_EXCINFO(&stash);
241 report_lost_exception_v(exc, why, ap);
242 RESTORE_EXCINFO(&stash);
243 va_end(ap);
244 }
245}
246
247/*----- Type definitions --------------------------------------------------*/
248
249static const PyTypeObject emptytype = { 0 };
250
251void *newtype(PyTypeObject *metaty,
252 const PyTypeObject *skel,
253 const char *name)
254{
255 PyHeapTypeObject *ty =
256 (PyHeapTypeObject *)_PyObject_GC_Malloc(_PyObject_VAR_SIZE(metaty, 0));
257 if (!skel) skel = &emptytype;
258 memcpy(ty, skel, sizeof(*skel));
c1756f78
MW
259#define COPY(blah) do { \
260 if (ty->ht_type.tp_as_##blah) { \
261 memcpy(&ty->as_##blah, \
262 ty->ht_type.tp_as_##blah, \
263 sizeof(ty->as_##blah)); \
264 ty->ht_type.tp_as_##blah = &ty->as_##blah; \
265 } \
266 } while (0)
267 COPY(number);
268 COPY(sequence);
269 COPY(mapping);
270 COPY(buffer);
271#undef COPY
272 if (name)
e0a7dece 273 ty->ht_name = TEXT_FROMSTR(name);
c1756f78 274 else if (ty->ht_type.tp_name)
e0a7dece
MW
275 ty->ht_name = TEXT_FROMSTR(ty->ht_type.tp_name);
276 else
277 ty->ht_name = 0;
c1756f78 278 if (ty->ht_name)
e0a7dece 279 ty->ht_type.tp_name = TEXT_STR(ty->ht_name);
1b026fd1 280 ty->ht_slots = 0;
c80de12d
MW
281#ifdef PY3
282 ty->ht_qualname = 0;
283#endif
c1756f78
MW
284 (void)PyObject_INIT(&ty->ht_type, metaty);
285 Py_INCREF(metaty);
286 return (ty);
287}
288
289void typeready(PyTypeObject *ty)
290{
c80de12d
MW
291#ifdef PY3
292 PyHeapTypeObject *hty = (PyHeapTypeObject *)ty;
293 hty->ht_qualname = hty->ht_name;
294#endif
c1756f78
MW
295 PyType_Ready(ty);
296 PyDict_SetItemString(ty->tp_dict, "__module__", modname);
297}
298
747ddb1b
MW
299PyTypeObject *inittype(const PyTypeObject *tyskel,
300 PyTypeObject *base, PyTypeObject *meta)
c1756f78
MW
301{
302 PyTypeObject *ty = newtype(meta, tyskel, 0);
747ddb1b 303 if (base) { ty->tp_base = base; Py_INCREF(base); }
c1756f78
MW
304 ty->tp_flags |= Py_TPFLAGS_HEAPTYPE;
305 typeready(ty);
306 return (ty);
307}
308
309/*----- Populating modules ------------------------------------------------*/
310
311PyObject *mkexc(PyObject *mod, PyObject *base,
87fa2d56 312 const char *name, const PyMethodDef *mm)
c1756f78
MW
313{
314 PyObject *nameobj = 0;
315 PyObject *dict = 0;
316 PyObject *exc = 0;
317 PyObject *func = 0;
318 PyObject *meth = 0;
319
320 if ((dict = PyDict_New()) == 0) goto fail;
321
322 if (mm) {
323 while (mm->ml_name) {
87fa2d56
MW
324 if ((func = PyCFunction_NewEx((/*unconst*/ PyMethodDef *)mm,
325 0, mod)) == 0 ||
c80de12d
MW
326 (meth = PY23(PyMethod_New(func, 0, exc),
327 PyInstanceMethod_New(func))) == 0 ||
c1756f78
MW
328 PyDict_SetItemString(dict, mm->ml_name, meth))
329 goto fail;
330 Py_DECREF(func); func = 0;
331 Py_DECREF(meth); meth = 0;
332 mm++;
333 }
334 }
335
e0a7dece
MW
336 if ((nameobj = TEXT_FORMAT("%s.%s", PyModule_GetName(mod), name)) == 0 ||
337 (exc = PyErr_NewException(TEXT_STR(nameobj), base, dict)) == 0)
c1756f78
MW
338 goto fail;
339
340done:
341 Py_XDECREF(nameobj);
342 Py_XDECREF(dict);
343 return (exc);
344
345fail:
346 Py_XDECREF(exc);
347 Py_XDECREF(func);
348 Py_XDECREF(meth);
349 exc = 0;
350 goto done;
351}
352
353void setconstants(PyObject *mod, const struct nameval *c)
354{
355 PyObject *x;
356 unsigned long u;
357
358 while (c->name) {
359 u = c->value;
360 if (u <= LONG_MAX) x = PyInt_FromLong(u);
361 else if (c->f&CF_SIGNED) x = PyInt_FromLong(-1 - (long)(ULONG_MAX - u));
362 else x = PyLong_FromUnsignedLong(u);
363 PyModule_AddObject(mod, (/*unconst*/ char *)c->name, x);
364 c++;
365 }
366}
367
368/*----- Submodules --------------------------------------------------------*/
369
370static PyMethodDef *global_methods;
371static size_t nmethods, methodsz;
372
373void addmethods(const PyMethodDef *m)
374{
375 size_t n, want, newsz;
376
377 for (n = 0; m[n].ml_name; n++);
378 want = nmethods + n + 1;
379 if (want > methodsz) {
380 newsz = methodsz ? 2*methodsz : 16;
381 while (want > newsz) newsz *= 2;
382 if (!global_methods)
383 global_methods = PyObject_Malloc(newsz*sizeof(PyMethodDef));
384 else
385 global_methods = PyObject_Realloc(global_methods,
386 newsz*sizeof(PyMethodDef));
387 assert(global_methods);
388 methodsz = newsz;
389 }
390 memcpy(global_methods + nmethods, m, n*sizeof(PyMethodDef));
391 nmethods += n;
392 global_methods[nmethods].ml_name = 0;
393}
394
395PyMethodDef *donemethods(void) { return (global_methods); }
396
397/*----- Low-level Python interface ----------------------------------------*/
398
399static PyObject *meth__set_home_module(PyObject *me, PyObject *arg)
400{
401 PyObject *mod;
402
403 if (!PyArg_ParseTuple(arg, "O!:_set_home_module", &PyModule_Type, &mod))
404 return (0);
405 Py_XDECREF(home_module); home_module = mod; Py_INCREF(home_module);
406 RETURN_NONE;
407}
408
409static const PyMethodDef methods[] = {
410#define METHNAME(func) meth_##func
411 METH (_set_home_module, "_set_home_module(MOD)")
412#undef METHNAME
413 { 0 }
414};
415
416void pyke_core_pyinit(void) { addmethods(methods); }
417void pyke_core_pyinsert(PyObject *mod) { ; }
418
419/*----- That's all, folks -------------------------------------------------*/