PageRenderTime 35ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/pypy/translator/c/src/support.h

https://bitbucket.org/pypy/pypy/
C Header | 519 lines | 436 code | 46 blank | 37 comment | 94 complexity | 0960cf268254fa073bdc6691522548cc MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  1. /************************************************************/
  2. /*** C header subsection: support functions ***/
  3. #include <stdio.h>
  4. /*** misc ***/
  5. #if !defined(MIN)
  6. #define MIN(a,b) (((a)<(b))?(a):(b))
  7. #endif /* MIN */
  8. #define RUNNING_ON_LLINTERP 0
  9. #define OP_JIT_RECORD_KNOWN_CLASS(i, c, r) /* nothing */
  10. #define FAIL_EXCEPTION(exc, msg) \
  11. { \
  12. RPyRaiseSimpleException(exc, msg); \
  13. }
  14. #define FAIL_OVF(msg) FAIL_EXCEPTION(PyExc_OverflowError, msg)
  15. #define FAIL_VAL(msg) FAIL_EXCEPTION(PyExc_ValueError, msg)
  16. #define FAIL_ZER(msg) FAIL_EXCEPTION(PyExc_ZeroDivisionError, msg)
  17. #define CFAIL() RPyConvertExceptionFromCPython()
  18. /* the following macros are used by rpython/lltypesystem/rstr.py */
  19. #define PyString_FromRPyString(rpystr) \
  20. PyString_FromStringAndSize(_RPyString_AsString(rpystr), RPyString_Size(rpystr))
  21. #define PyUnicode_FromRPyUnicode(rpystr) \
  22. _PyUnicode_FromRPyUnicode(_RPyUnicode_AsUnicode(rpystr), RPyUnicode_Size(rpystr))
  23. #define PyString_ToRPyString(s, rpystr) \
  24. memcpy(_RPyString_AsString(rpystr), PyString_AS_STRING(s), \
  25. RPyString_Size(rpystr))
  26. /* Extra checks can be enabled with the RPY_ASSERT or RPY_LL_ASSERT
  27. * macros. They differ in the level at which the tests are made.
  28. * Remember that RPython lists, for example, are implemented as a
  29. * GcStruct pointing to an over-allocated GcArray. With RPY_ASSERT you
  30. * get list index out of bound checks from rlist.py; such tests must be
  31. * manually written so made we've forgotten a case. Conversely, with
  32. * RPY_LL_ASSERT, all GcArray indexing are checked, which is safer
  33. * against attacks and segfaults - but less precise in the case of
  34. * lists, because of the overallocated bit.
  35. *
  36. * For extra safety, in programs translated with --sandbox we always
  37. * assume that we want RPY_LL_ASSERT. You can change it below to trade
  38. * safety for performance, though the hit is not huge (~10%?).
  39. */
  40. #ifdef RPY_ASSERT
  41. # define RPyAssert(x, msg) \
  42. if (!(x)) RPyAssertFailed(__FILE__, __LINE__, __FUNCTION__, msg)
  43. void RPyAssertFailed(const char* filename, long lineno,
  44. const char* function, const char *msg);
  45. # ifndef PYPY_NOT_MAIN_FILE
  46. void RPyAssertFailed(const char* filename, long lineno,
  47. const char* function, const char *msg) {
  48. fprintf(stderr,
  49. "PyPy assertion failed at %s:%ld:\n"
  50. "in %s: %s\n",
  51. filename, lineno, function, msg);
  52. abort();
  53. }
  54. # endif
  55. #else
  56. # define RPyAssert(x, msg) /* nothing */
  57. #endif
  58. #if defined(RPY_LL_ASSERT) || defined(RPY_SANDBOXED)
  59. /* obscure macros that can be used as expressions and lvalues to refer
  60. * to a field of a structure or an item in an array in a "safe" way --
  61. * they abort() in case of null pointer or out-of-bounds index. As a
  62. * speed trade-off, RPyItem actually segfaults if the array is null, but
  63. * it's a "guaranteed" segfault and not one that can be used by
  64. * attackers.
  65. */
  66. # define RPyCHECK(x) ((x)?(void)0:RPyAbort())
  67. # define RPyField(ptr, name) ((RPyCHECK(ptr), (ptr))->name)
  68. # define RPyItem(array, index) \
  69. ((RPyCHECK((index) >= 0 && (index) < (array)->length), \
  70. (array))->items[index])
  71. # define RPyFxItem(ptr, index, fixedsize) \
  72. ((RPyCHECK((ptr) && (index) >= 0 && (index) < (fixedsize)), \
  73. (ptr))[index])
  74. # define RPyNLenItem(array, index) \
  75. ((RPyCHECK((array) && (index) >= 0), (array))->items[index])
  76. # define RPyBareItem(array, index) \
  77. ((RPyCHECK((array) && (index) >= 0), (array))[index])
  78. void RPyAbort(void);
  79. #ifndef PYPY_NOT_MAIN_FILE
  80. void RPyAbort(void) {
  81. fprintf(stderr, "Invalid RPython operation (NULL ptr or bad array index)\n");
  82. abort();
  83. }
  84. #endif
  85. #else
  86. # define RPyField(ptr, name) ((ptr)->name)
  87. # define RPyItem(array, index) ((array)->items[index])
  88. # define RPyFxItem(ptr, index, fixedsize) ((ptr)[index])
  89. # define RPyNLenItem(array, index) ((array)->items[index])
  90. # define RPyBareItem(array, index) ((array)[index])
  91. #endif
  92. #ifndef PYPY_STANDALONE
  93. /* prototypes */
  94. PyObject * gencfunc_descr_get(PyObject *func, PyObject *obj, PyObject *type);
  95. PyObject* PyList_Pack(int n, ...);
  96. PyObject* PyDict_Pack(int n, ...);
  97. #if PY_VERSION_HEX < 0x02040000 /* 2.4 */
  98. PyObject* PyTuple_Pack(int n, ...);
  99. #endif
  100. #if PY_VERSION_HEX >= 0x02030000 /* 2.3 */
  101. # define PyObject_GetItem1 PyObject_GetItem
  102. # define PyObject_SetItem1 PyObject_SetItem
  103. #else
  104. PyObject* PyObject_GetItem1(PyObject* obj, PyObject* index);
  105. PyObject* PyObject_SetItem1(PyObject* obj, PyObject* index, PyObject* v);
  106. #endif
  107. PyObject* CallWithShape(PyObject* callable, PyObject* shape, ...);
  108. PyObject* decode_arg(PyObject* fname, int position, PyObject* name,
  109. PyObject* vargs, PyObject* vkwds, PyObject* def);
  110. int check_no_more_arg(PyObject* fname, int n, PyObject* vargs);
  111. int check_self_nonzero(PyObject* fname, PyObject* self);
  112. PyObject *PyTuple_GetItem_WithIncref(PyObject *tuple, int index);
  113. int PyTuple_SetItem_WithIncref(PyObject *tuple, int index, PyObject *o);
  114. int PySequence_Contains_with_exc(PyObject *seq, PyObject *ob);
  115. PyObject* _PyUnicode_FromRPyUnicode(wchar_t *items, long length);
  116. /* implementations */
  117. #ifndef PYPY_NOT_MAIN_FILE
  118. /* we need a subclass of 'builtin_function_or_method' which can be used
  119. as methods: builtin function objects that can be bound on instances */
  120. PyObject *
  121. gencfunc_descr_get(PyObject *func, PyObject *obj, PyObject *type)
  122. {
  123. if (obj == Py_None)
  124. obj = NULL;
  125. return PyMethod_New(func, obj, type);
  126. }
  127. static PyTypeObject PyGenCFunction_Type = {
  128. PyObject_HEAD_INIT(NULL)
  129. 0,
  130. "pypy_generated_function",
  131. sizeof(PyCFunctionObject),
  132. 0,
  133. 0, /* tp_dealloc */
  134. 0, /* tp_print */
  135. 0, /* tp_getattr */
  136. 0, /* tp_setattr */
  137. 0, /* tp_compare */
  138. 0, /* tp_repr */
  139. 0, /* tp_as_number */
  140. 0, /* tp_as_sequence */
  141. 0, /* tp_as_mapping */
  142. 0, /* tp_hash */
  143. 0, /* tp_call */
  144. 0, /* tp_str */
  145. 0, /* tp_getattro */
  146. 0, /* tp_setattro */
  147. 0, /* tp_as_buffer */
  148. Py_TPFLAGS_DEFAULT, /* tp_flags */
  149. 0, /* tp_doc */
  150. 0, /* tp_traverse */
  151. 0, /* tp_clear */
  152. 0, /* tp_richcompare */
  153. 0, /* tp_weaklistoffset */
  154. 0, /* tp_iter */
  155. 0, /* tp_iternext */
  156. 0, /* tp_methods */
  157. 0, /* tp_members */
  158. 0, /* tp_getset */
  159. /*&PyCFunction_Type set below*/ 0, /* tp_base */
  160. 0, /* tp_dict */
  161. gencfunc_descr_get, /* tp_descr_get */
  162. 0, /* tp_descr_set */
  163. };
  164. /*** misc support functions ***/
  165. PyObject* PyList_Pack(int n, ...)
  166. {
  167. int i;
  168. PyObject *o;
  169. PyObject *result;
  170. va_list vargs;
  171. va_start(vargs, n);
  172. result = PyList_New(n);
  173. if (result == NULL) {
  174. return NULL;
  175. }
  176. for (i = 0; i < n; i++) {
  177. o = va_arg(vargs, PyObject *);
  178. Py_INCREF(o);
  179. PyList_SET_ITEM(result, i, o);
  180. }
  181. va_end(vargs);
  182. return result;
  183. }
  184. PyObject* PyDict_Pack(int n, ...)
  185. {
  186. int i;
  187. PyObject *key, *val;
  188. PyObject *result;
  189. va_list vargs;
  190. va_start(vargs, n);
  191. result = PyDict_New();
  192. if (result == NULL) {
  193. return NULL;
  194. }
  195. for (i = 0; i < n; i++) {
  196. key = va_arg(vargs, PyObject *);
  197. val = va_arg(vargs, PyObject *);
  198. if (PyDict_SetItem(result, key, val) < 0) {
  199. Py_DECREF(result);
  200. return NULL;
  201. }
  202. }
  203. va_end(vargs);
  204. return result;
  205. }
  206. #if PY_VERSION_HEX < 0x02040000 /* 2.4 */
  207. PyObject* PyTuple_Pack(int n, ...)
  208. {
  209. int i;
  210. PyObject *o;
  211. PyObject *result;
  212. PyObject **items;
  213. va_list vargs;
  214. va_start(vargs, n);
  215. result = PyTuple_New(n);
  216. if (result == NULL) {
  217. return NULL;
  218. }
  219. items = ((PyTupleObject *)result)->ob_item;
  220. for (i = 0; i < n; i++) {
  221. o = va_arg(vargs, PyObject *);
  222. Py_INCREF(o);
  223. items[i] = o;
  224. }
  225. va_end(vargs);
  226. return result;
  227. }
  228. #endif
  229. #if PY_VERSION_HEX < 0x02030000 /* 2.3 */
  230. /* for Python 2.2 only */
  231. PyObject* PyObject_GetItem1(PyObject* obj, PyObject* index)
  232. {
  233. int start, stop, step;
  234. if (!PySlice_Check(index)) {
  235. return PyObject_GetItem(obj, index);
  236. }
  237. if (((PySliceObject*) index)->start == Py_None) {
  238. start = -INT_MAX-1;
  239. } else {
  240. start = PyInt_AsLong(((PySliceObject*) index)->start);
  241. if (start == -1 && PyErr_Occurred()) {
  242. return NULL;
  243. }
  244. }
  245. if (((PySliceObject*) index)->stop == Py_None) {
  246. stop = INT_MAX;
  247. } else {
  248. stop = PyInt_AsLong(((PySliceObject*) index)->stop);
  249. if (stop == -1 && PyErr_Occurred()) {
  250. return NULL;
  251. }
  252. }
  253. if (((PySliceObject*) index)->step != Py_None) {
  254. step = PyInt_AsLong(((PySliceObject*) index)->step);
  255. if (step == -1 && PyErr_Occurred()) {
  256. return NULL;
  257. }
  258. if (step != 1) {
  259. PyErr_SetString(PyExc_ValueError,
  260. "obj[slice]: no step allowed");
  261. return NULL;
  262. }
  263. }
  264. return PySequence_GetSlice(obj, start, stop);
  265. }
  266. PyObject* PyObject_SetItem1(PyObject* obj, PyObject* index, PyObject* v)
  267. {
  268. int start, stop, step;
  269. if (!PySlice_Check(index)) {
  270. return PyObject_SetItem(obj, index, v);
  271. }
  272. if (((PySliceObject*) index)->start == Py_None) {
  273. start = -INT_MAX-1;
  274. } else {
  275. start = PyInt_AsLong(((PySliceObject*) index)->start);
  276. if (start == -1 && PyErr_Occurred()) {
  277. return NULL;
  278. }
  279. }
  280. if (((PySliceObject*) index)->stop == Py_None) {
  281. stop = INT_MAX;
  282. } else {
  283. stop = PyInt_AsLong(((PySliceObject*) index)->stop);
  284. if (stop == -1 && PyErr_Occurred()) {
  285. return NULL;
  286. }
  287. }
  288. if (((PySliceObject*) index)->step != Py_None) {
  289. step = PyInt_AsLong(((PySliceObject*) index)->step);
  290. if (step == -1 && PyErr_Occurred()) {
  291. return NULL;
  292. }
  293. if (step != 1) {
  294. PyErr_SetString(PyExc_ValueError,
  295. "obj[slice]: no step allowed");
  296. return NULL;
  297. }
  298. }
  299. return PySequence_SetSlice(obj, start, stop, v);
  300. }
  301. #endif
  302. PyObject* CallWithShape(PyObject* callable, PyObject* shape, ...)
  303. {
  304. /* XXX the 'shape' argument is a tuple as specified by
  305. XXX pypy.interpreter.argument.fromshape(). This code should
  306. XXX we made independent on the format of the 'shape' later... */
  307. PyObject* result = NULL;
  308. PyObject* t = NULL;
  309. PyObject* d = NULL;
  310. PyObject* o;
  311. PyObject* key;
  312. PyObject* t2;
  313. int i, nargs, nkwds, starflag, starstarflag;
  314. va_list vargs;
  315. if (!PyTuple_Check(shape) ||
  316. PyTuple_GET_SIZE(shape) != 4 ||
  317. !PyInt_Check(PyTuple_GET_ITEM(shape, 0)) ||
  318. !PyTuple_Check(PyTuple_GET_ITEM(shape, 1)) ||
  319. !PyInt_Check(PyTuple_GET_ITEM(shape, 2)) ||
  320. !PyInt_Check(PyTuple_GET_ITEM(shape, 3))) {
  321. Py_FatalError("in genc.h: invalid 'shape' argument");
  322. }
  323. nargs = PyInt_AS_LONG(PyTuple_GET_ITEM(shape, 0));
  324. nkwds = PyTuple_GET_SIZE(PyTuple_GET_ITEM(shape, 1));
  325. starflag = PyInt_AS_LONG(PyTuple_GET_ITEM(shape, 2));
  326. starstarflag = PyInt_AS_LONG(PyTuple_GET_ITEM(shape, 3));
  327. va_start(vargs, shape);
  328. t = PyTuple_New(nargs);
  329. if (t == NULL)
  330. goto finally;
  331. for (i = 0; i < nargs; i++) {
  332. o = va_arg(vargs, PyObject *);
  333. Py_INCREF(o);
  334. PyTuple_SET_ITEM(t, i, o);
  335. }
  336. if (nkwds) {
  337. d = PyDict_New();
  338. if (d == NULL)
  339. goto finally;
  340. for (i = 0; i < nkwds; i++) {
  341. o = va_arg(vargs, PyObject *);
  342. key = PyTuple_GET_ITEM(PyTuple_GET_ITEM(shape, 1), i);
  343. if (PyDict_SetItem(d, key, o) < 0)
  344. goto finally;
  345. }
  346. }
  347. if (starflag) {
  348. o = va_arg(vargs, PyObject *);
  349. o = PySequence_Tuple(o);
  350. if (o == NULL)
  351. goto finally;
  352. t2 = PySequence_Concat(t, o);
  353. Py_DECREF(o);
  354. Py_DECREF(t);
  355. t = t2;
  356. if (t == NULL)
  357. goto finally;
  358. }
  359. if (starstarflag) {
  360. int len1, len2, len3;
  361. o = va_arg(vargs, PyObject *);
  362. len1 = PyDict_Size(d);
  363. len2 = PyDict_Size(o);
  364. if (len1 < 0 || len2 < 0)
  365. goto finally;
  366. if (PyDict_Update(d, o) < 0)
  367. goto finally;
  368. len3 = PyDict_Size(d);
  369. if (len1 + len2 != len3) {
  370. PyErr_SetString(PyExc_TypeError,
  371. "genc.h: duplicate keyword arguments");
  372. goto finally;
  373. }
  374. }
  375. va_end(vargs);
  376. result = PyObject_Call(callable, t, d);
  377. finally:
  378. Py_XDECREF(d);
  379. Py_XDECREF(t);
  380. return result;
  381. }
  382. PyObject* decode_arg(PyObject* fname, int position, PyObject* name,
  383. PyObject* vargs, PyObject* vkwds, PyObject* def)
  384. {
  385. PyObject* result;
  386. int size = PyTuple_Size(vargs);
  387. if (size < 0)
  388. return NULL;
  389. if (vkwds != NULL) {
  390. result = PyDict_GetItem(vkwds, name);
  391. if (result != NULL) {
  392. if (position < size) {
  393. PyErr_Format(PyExc_TypeError,
  394. "%s() got duplicate value for "
  395. "its '%s' argument",
  396. PyString_AS_STRING(fname),
  397. PyString_AS_STRING(name));
  398. return NULL;
  399. }
  400. Py_INCREF(result);
  401. return result;
  402. }
  403. }
  404. if (position < size) {
  405. /* common case */
  406. result = PyTuple_GET_ITEM(vargs, position);
  407. Py_INCREF(result);
  408. return result;
  409. }
  410. if (def != NULL) {
  411. Py_INCREF(def);
  412. return def;
  413. }
  414. PyErr_Format(PyExc_TypeError, "%s() got only %d argument(s)",
  415. PyString_AS_STRING(fname),
  416. position);
  417. return NULL;
  418. }
  419. int check_no_more_arg(PyObject* fname, int n, PyObject* vargs)
  420. {
  421. int size = PyTuple_Size(vargs);
  422. if (size < 0)
  423. return -1;
  424. if (size > n) {
  425. PyErr_Format(PyExc_TypeError,
  426. "%s() got %d argument(s), expected %d",
  427. PyString_AS_STRING(fname),
  428. size, n);
  429. return -1;
  430. }
  431. return 0;
  432. }
  433. int check_self_nonzero(PyObject* fname, PyObject* self)
  434. {
  435. if (!self) {
  436. PyErr_Format(PyExc_TypeError,
  437. "%s() expects instance first arg",
  438. PyString_AS_STRING(fname));
  439. return -1;
  440. }
  441. return 0;
  442. }
  443. /************************************************************/
  444. PyObject *PyTuple_GetItem_WithIncref(PyObject *tuple, int index)
  445. {
  446. PyObject *result = PyTuple_GetItem(tuple, index);
  447. Py_XINCREF(result);
  448. return result;
  449. }
  450. int PyTuple_SetItem_WithIncref(PyObject *tuple, int index, PyObject *o)
  451. {
  452. Py_INCREF(o);
  453. return PyTuple_SetItem(tuple, index, o);
  454. }
  455. int PySequence_Contains_with_exc(PyObject *seq, PyObject *ob)
  456. {
  457. int ret = PySequence_Contains(seq, ob);
  458. if (ret < 0)
  459. CFAIL();
  460. return ret;
  461. }
  462. PyObject* _PyUnicode_FromRPyUnicode(wchar_t *items, long length)
  463. {
  464. PyObject *u = PyUnicode_FromUnicode(NULL, length);
  465. long i;
  466. for (i=0; i<length; i++) {
  467. /* xxx possibly silently truncate the unichars */
  468. PyUnicode_AS_UNICODE(u)[i] = items[i];
  469. }
  470. return u;
  471. }
  472. #endif /* PYPY_STANDALONE */
  473. #endif /* PYPY_NOT_MAIN_FILE */