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

/Python/modsupport.c

https://bitbucket.org/glix/python
C | 643 lines | 534 code | 64 blank | 45 comment | 126 complexity | 41e203c761fbb1a062e29947e8f09fdd MD5 | raw file
  1. /* Module support implementation */
  2. #include "Python.h"
  3. #define FLAG_SIZE_T 1
  4. typedef double va_double;
  5. static PyObject *va_build_value(const char *, va_list, int);
  6. /* Package context -- the full module name for package imports */
  7. char *_Py_PackageContext = NULL;
  8. /* Py_InitModule4() parameters:
  9. - name is the module name
  10. - methods is the list of top-level functions
  11. - doc is the documentation string
  12. - passthrough is passed as self to functions defined in the module
  13. - api_version is the value of PYTHON_API_VERSION at the time the
  14. module was compiled
  15. Return value is a borrowed reference to the module object; or NULL
  16. if an error occurred (in Python 1.4 and before, errors were fatal).
  17. Errors may still leak memory.
  18. */
  19. static char api_version_warning[] =
  20. "Python C API version mismatch for module %.100s:\
  21. This Python has API version %d, module %.100s has version %d.";
  22. PyObject *
  23. Py_InitModule4(const char *name, PyMethodDef *methods, const char *doc,
  24. PyObject *passthrough, int module_api_version)
  25. {
  26. PyObject *m, *d, *v, *n;
  27. PyMethodDef *ml;
  28. if (!Py_IsInitialized())
  29. Py_FatalError("Interpreter not initialized (version mismatch?)");
  30. if (module_api_version != PYTHON_API_VERSION) {
  31. char message[512];
  32. PyOS_snprintf(message, sizeof(message),
  33. api_version_warning, name,
  34. PYTHON_API_VERSION, name,
  35. module_api_version);
  36. if (PyErr_Warn(PyExc_RuntimeWarning, message))
  37. return NULL;
  38. }
  39. /* Make sure name is fully qualified.
  40. This is a bit of a hack: when the shared library is loaded,
  41. the module name is "package.module", but the module calls
  42. Py_InitModule*() with just "module" for the name. The shared
  43. library loader squirrels away the true name of the module in
  44. _Py_PackageContext, and Py_InitModule*() will substitute this
  45. (if the name actually matches).
  46. */
  47. if (_Py_PackageContext != NULL) {
  48. char *p = strrchr(_Py_PackageContext, '.');
  49. if (p != NULL && strcmp(name, p+1) == 0) {
  50. name = _Py_PackageContext;
  51. _Py_PackageContext = NULL;
  52. }
  53. }
  54. if ((m = PyImport_AddModule(name)) == NULL)
  55. return NULL;
  56. d = PyModule_GetDict(m);
  57. if (methods != NULL) {
  58. n = PyString_FromString(name);
  59. if (n == NULL)
  60. return NULL;
  61. for (ml = methods; ml->ml_name != NULL; ml++) {
  62. if ((ml->ml_flags & METH_CLASS) ||
  63. (ml->ml_flags & METH_STATIC)) {
  64. PyErr_SetString(PyExc_ValueError,
  65. "module functions cannot set"
  66. " METH_CLASS or METH_STATIC");
  67. Py_DECREF(n);
  68. return NULL;
  69. }
  70. v = PyCFunction_NewEx(ml, passthrough, n);
  71. if (v == NULL) {
  72. Py_DECREF(n);
  73. return NULL;
  74. }
  75. if (PyDict_SetItemString(d, ml->ml_name, v) != 0) {
  76. Py_DECREF(v);
  77. Py_DECREF(n);
  78. return NULL;
  79. }
  80. Py_DECREF(v);
  81. }
  82. Py_DECREF(n);
  83. }
  84. if (doc != NULL) {
  85. v = PyString_FromString(doc);
  86. if (v == NULL || PyDict_SetItemString(d, "__doc__", v) != 0) {
  87. Py_XDECREF(v);
  88. return NULL;
  89. }
  90. Py_DECREF(v);
  91. }
  92. return m;
  93. }
  94. /* Helper for mkvalue() to scan the length of a format */
  95. static int
  96. countformat(const char *format, int endchar)
  97. {
  98. int count = 0;
  99. int level = 0;
  100. while (level > 0 || *format != endchar) {
  101. switch (*format) {
  102. case '\0':
  103. /* Premature end */
  104. PyErr_SetString(PyExc_SystemError,
  105. "unmatched paren in format");
  106. return -1;
  107. case '(':
  108. case '[':
  109. case '{':
  110. if (level == 0)
  111. count++;
  112. level++;
  113. break;
  114. case ')':
  115. case ']':
  116. case '}':
  117. level--;
  118. break;
  119. case '#':
  120. case '&':
  121. case ',':
  122. case ':':
  123. case ' ':
  124. case '\t':
  125. break;
  126. default:
  127. if (level == 0)
  128. count++;
  129. }
  130. format++;
  131. }
  132. return count;
  133. }
  134. /* Generic function to create a value -- the inverse of getargs() */
  135. /* After an original idea and first implementation by Steven Miale */
  136. static PyObject *do_mktuple(const char**, va_list *, int, int, int);
  137. static PyObject *do_mklist(const char**, va_list *, int, int, int);
  138. static PyObject *do_mkdict(const char**, va_list *, int, int, int);
  139. static PyObject *do_mkvalue(const char**, va_list *, int);
  140. static PyObject *
  141. do_mkdict(const char **p_format, va_list *p_va, int endchar, int n, int flags)
  142. {
  143. PyObject *d;
  144. int i;
  145. int itemfailed = 0;
  146. if (n < 0)
  147. return NULL;
  148. if ((d = PyDict_New()) == NULL)
  149. return NULL;
  150. /* Note that we can't bail immediately on error as this will leak
  151. refcounts on any 'N' arguments. */
  152. for (i = 0; i < n; i+= 2) {
  153. PyObject *k, *v;
  154. int err;
  155. k = do_mkvalue(p_format, p_va, flags);
  156. if (k == NULL) {
  157. itemfailed = 1;
  158. Py_INCREF(Py_None);
  159. k = Py_None;
  160. }
  161. v = do_mkvalue(p_format, p_va, flags);
  162. if (v == NULL) {
  163. itemfailed = 1;
  164. Py_INCREF(Py_None);
  165. v = Py_None;
  166. }
  167. err = PyDict_SetItem(d, k, v);
  168. Py_DECREF(k);
  169. Py_DECREF(v);
  170. if (err < 0 || itemfailed) {
  171. Py_DECREF(d);
  172. return NULL;
  173. }
  174. }
  175. if (d != NULL && **p_format != endchar) {
  176. Py_DECREF(d);
  177. d = NULL;
  178. PyErr_SetString(PyExc_SystemError,
  179. "Unmatched paren in format");
  180. }
  181. else if (endchar)
  182. ++*p_format;
  183. return d;
  184. }
  185. static PyObject *
  186. do_mklist(const char **p_format, va_list *p_va, int endchar, int n, int flags)
  187. {
  188. PyObject *v;
  189. int i;
  190. int itemfailed = 0;
  191. if (n < 0)
  192. return NULL;
  193. v = PyList_New(n);
  194. if (v == NULL)
  195. return NULL;
  196. /* Note that we can't bail immediately on error as this will leak
  197. refcounts on any 'N' arguments. */
  198. for (i = 0; i < n; i++) {
  199. PyObject *w = do_mkvalue(p_format, p_va, flags);
  200. if (w == NULL) {
  201. itemfailed = 1;
  202. Py_INCREF(Py_None);
  203. w = Py_None;
  204. }
  205. PyList_SET_ITEM(v, i, w);
  206. }
  207. if (itemfailed) {
  208. /* do_mkvalue() should have already set an error */
  209. Py_DECREF(v);
  210. return NULL;
  211. }
  212. if (**p_format != endchar) {
  213. Py_DECREF(v);
  214. PyErr_SetString(PyExc_SystemError,
  215. "Unmatched paren in format");
  216. return NULL;
  217. }
  218. if (endchar)
  219. ++*p_format;
  220. return v;
  221. }
  222. #ifdef Py_USING_UNICODE
  223. static int
  224. _ustrlen(Py_UNICODE *u)
  225. {
  226. int i = 0;
  227. Py_UNICODE *v = u;
  228. while (*v != 0) { i++; v++; }
  229. return i;
  230. }
  231. #endif
  232. static PyObject *
  233. do_mktuple(const char **p_format, va_list *p_va, int endchar, int n, int flags)
  234. {
  235. PyObject *v;
  236. int i;
  237. int itemfailed = 0;
  238. if (n < 0)
  239. return NULL;
  240. if ((v = PyTuple_New(n)) == NULL)
  241. return NULL;
  242. /* Note that we can't bail immediately on error as this will leak
  243. refcounts on any 'N' arguments. */
  244. for (i = 0; i < n; i++) {
  245. PyObject *w = do_mkvalue(p_format, p_va, flags);
  246. if (w == NULL) {
  247. itemfailed = 1;
  248. Py_INCREF(Py_None);
  249. w = Py_None;
  250. }
  251. PyTuple_SET_ITEM(v, i, w);
  252. }
  253. if (itemfailed) {
  254. /* do_mkvalue() should have already set an error */
  255. Py_DECREF(v);
  256. return NULL;
  257. }
  258. if (**p_format != endchar) {
  259. Py_DECREF(v);
  260. PyErr_SetString(PyExc_SystemError,
  261. "Unmatched paren in format");
  262. return NULL;
  263. }
  264. if (endchar)
  265. ++*p_format;
  266. return v;
  267. }
  268. static PyObject *
  269. do_mkvalue(const char **p_format, va_list *p_va, int flags)
  270. {
  271. for (;;) {
  272. switch (*(*p_format)++) {
  273. case '(':
  274. return do_mktuple(p_format, p_va, ')',
  275. countformat(*p_format, ')'), flags);
  276. case '[':
  277. return do_mklist(p_format, p_va, ']',
  278. countformat(*p_format, ']'), flags);
  279. case '{':
  280. return do_mkdict(p_format, p_va, '}',
  281. countformat(*p_format, '}'), flags);
  282. case 'b':
  283. case 'B':
  284. case 'h':
  285. case 'i':
  286. return PyInt_FromLong((long)va_arg(*p_va, int));
  287. case 'H':
  288. return PyInt_FromLong((long)va_arg(*p_va, unsigned int));
  289. case 'I':
  290. {
  291. unsigned int n;
  292. n = va_arg(*p_va, unsigned int);
  293. if (n > (unsigned long)PyInt_GetMax())
  294. return PyLong_FromUnsignedLong((unsigned long)n);
  295. else
  296. return PyInt_FromLong(n);
  297. }
  298. case 'n':
  299. #if SIZEOF_SIZE_T!=SIZEOF_LONG
  300. return PyInt_FromSsize_t(va_arg(*p_va, Py_ssize_t));
  301. #endif
  302. /* Fall through from 'n' to 'l' if Py_ssize_t is long */
  303. case 'l':
  304. return PyInt_FromLong(va_arg(*p_va, long));
  305. case 'k':
  306. {
  307. unsigned long n;
  308. n = va_arg(*p_va, unsigned long);
  309. if (n > (unsigned long)PyInt_GetMax())
  310. return PyLong_FromUnsignedLong(n);
  311. else
  312. return PyInt_FromLong(n);
  313. }
  314. #ifdef HAVE_LONG_LONG
  315. case 'L':
  316. return PyLong_FromLongLong((PY_LONG_LONG)va_arg(*p_va, PY_LONG_LONG));
  317. case 'K':
  318. return PyLong_FromUnsignedLongLong((PY_LONG_LONG)va_arg(*p_va, unsigned PY_LONG_LONG));
  319. #endif
  320. #ifdef Py_USING_UNICODE
  321. case 'u':
  322. {
  323. PyObject *v;
  324. Py_UNICODE *u = va_arg(*p_va, Py_UNICODE *);
  325. Py_ssize_t n;
  326. if (**p_format == '#') {
  327. ++*p_format;
  328. if (flags & FLAG_SIZE_T)
  329. n = va_arg(*p_va, Py_ssize_t);
  330. else
  331. n = va_arg(*p_va, int);
  332. }
  333. else
  334. n = -1;
  335. if (u == NULL) {
  336. v = Py_None;
  337. Py_INCREF(v);
  338. }
  339. else {
  340. if (n < 0)
  341. n = _ustrlen(u);
  342. v = PyUnicode_FromUnicode(u, n);
  343. }
  344. return v;
  345. }
  346. #endif
  347. case 'f':
  348. case 'd':
  349. return PyFloat_FromDouble(
  350. (double)va_arg(*p_va, va_double));
  351. #ifndef WITHOUT_COMPLEX
  352. case 'D':
  353. return PyComplex_FromCComplex(
  354. *((Py_complex *)va_arg(*p_va, Py_complex *)));
  355. #endif /* WITHOUT_COMPLEX */
  356. case 'c':
  357. {
  358. char p[1];
  359. p[0] = (char)va_arg(*p_va, int);
  360. return PyString_FromStringAndSize(p, 1);
  361. }
  362. case 's':
  363. case 'z':
  364. {
  365. PyObject *v;
  366. char *str = va_arg(*p_va, char *);
  367. Py_ssize_t n;
  368. if (**p_format == '#') {
  369. ++*p_format;
  370. if (flags & FLAG_SIZE_T)
  371. n = va_arg(*p_va, Py_ssize_t);
  372. else
  373. n = va_arg(*p_va, int);
  374. }
  375. else
  376. n = -1;
  377. if (str == NULL) {
  378. v = Py_None;
  379. Py_INCREF(v);
  380. }
  381. else {
  382. if (n < 0) {
  383. size_t m = strlen(str);
  384. if (m > PY_SSIZE_T_MAX) {
  385. PyErr_SetString(PyExc_OverflowError,
  386. "string too long for Python string");
  387. return NULL;
  388. }
  389. n = (Py_ssize_t)m;
  390. }
  391. v = PyString_FromStringAndSize(str, n);
  392. }
  393. return v;
  394. }
  395. case 'N':
  396. case 'S':
  397. case 'O':
  398. if (**p_format == '&') {
  399. typedef PyObject *(*converter)(void *);
  400. converter func = va_arg(*p_va, converter);
  401. void *arg = va_arg(*p_va, void *);
  402. ++*p_format;
  403. return (*func)(arg);
  404. }
  405. else {
  406. PyObject *v;
  407. v = va_arg(*p_va, PyObject *);
  408. if (v != NULL) {
  409. if (*(*p_format - 1) != 'N')
  410. Py_INCREF(v);
  411. }
  412. else if (!PyErr_Occurred())
  413. /* If a NULL was passed
  414. * because a call that should
  415. * have constructed a value
  416. * failed, that's OK, and we
  417. * pass the error on; but if
  418. * no error occurred it's not
  419. * clear that the caller knew
  420. * what she was doing. */
  421. PyErr_SetString(PyExc_SystemError,
  422. "NULL object passed to Py_BuildValue");
  423. return v;
  424. }
  425. case ':':
  426. case ',':
  427. case ' ':
  428. case '\t':
  429. break;
  430. default:
  431. PyErr_SetString(PyExc_SystemError,
  432. "bad format char passed to Py_BuildValue");
  433. return NULL;
  434. }
  435. }
  436. }
  437. PyObject *
  438. Py_BuildValue(const char *format, ...)
  439. {
  440. va_list va;
  441. PyObject* retval;
  442. va_start(va, format);
  443. retval = va_build_value(format, va, 0);
  444. va_end(va);
  445. return retval;
  446. }
  447. PyObject *
  448. _Py_BuildValue_SizeT(const char *format, ...)
  449. {
  450. va_list va;
  451. PyObject* retval;
  452. va_start(va, format);
  453. retval = va_build_value(format, va, FLAG_SIZE_T);
  454. va_end(va);
  455. return retval;
  456. }
  457. PyObject *
  458. Py_VaBuildValue(const char *format, va_list va)
  459. {
  460. return va_build_value(format, va, 0);
  461. }
  462. PyObject *
  463. _Py_VaBuildValue_SizeT(const char *format, va_list va)
  464. {
  465. return va_build_value(format, va, FLAG_SIZE_T);
  466. }
  467. static PyObject *
  468. va_build_value(const char *format, va_list va, int flags)
  469. {
  470. const char *f = format;
  471. int n = countformat(f, '\0');
  472. va_list lva;
  473. #ifdef VA_LIST_IS_ARRAY
  474. memcpy(lva, va, sizeof(va_list));
  475. #else
  476. #ifdef __va_copy
  477. __va_copy(lva, va);
  478. #else
  479. lva = va;
  480. #endif
  481. #endif
  482. if (n < 0)
  483. return NULL;
  484. if (n == 0) {
  485. Py_INCREF(Py_None);
  486. return Py_None;
  487. }
  488. if (n == 1)
  489. return do_mkvalue(&f, &lva, flags);
  490. return do_mktuple(&f, &lva, '\0', n, flags);
  491. }
  492. PyObject *
  493. PyEval_CallFunction(PyObject *obj, const char *format, ...)
  494. {
  495. va_list vargs;
  496. PyObject *args;
  497. PyObject *res;
  498. va_start(vargs, format);
  499. args = Py_VaBuildValue(format, vargs);
  500. va_end(vargs);
  501. if (args == NULL)
  502. return NULL;
  503. res = PyEval_CallObject(obj, args);
  504. Py_DECREF(args);
  505. return res;
  506. }
  507. PyObject *
  508. PyEval_CallMethod(PyObject *obj, const char *methodname, const char *format, ...)
  509. {
  510. va_list vargs;
  511. PyObject *meth;
  512. PyObject *args;
  513. PyObject *res;
  514. meth = PyObject_GetAttrString(obj, methodname);
  515. if (meth == NULL)
  516. return NULL;
  517. va_start(vargs, format);
  518. args = Py_VaBuildValue(format, vargs);
  519. va_end(vargs);
  520. if (args == NULL) {
  521. Py_DECREF(meth);
  522. return NULL;
  523. }
  524. res = PyEval_CallObject(meth, args);
  525. Py_DECREF(meth);
  526. Py_DECREF(args);
  527. return res;
  528. }
  529. int
  530. PyModule_AddObject(PyObject *m, const char *name, PyObject *o)
  531. {
  532. PyObject *dict;
  533. if (!PyModule_Check(m)) {
  534. PyErr_SetString(PyExc_TypeError,
  535. "PyModule_AddObject() needs module as first arg");
  536. return -1;
  537. }
  538. if (!o) {
  539. if (!PyErr_Occurred())
  540. PyErr_SetString(PyExc_TypeError,
  541. "PyModule_AddObject() needs non-NULL value");
  542. return -1;
  543. }
  544. dict = PyModule_GetDict(m);
  545. if (dict == NULL) {
  546. /* Internal error -- modules must have a dict! */
  547. PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__",
  548. PyModule_GetName(m));
  549. return -1;
  550. }
  551. if (PyDict_SetItemString(dict, name, o))
  552. return -1;
  553. Py_DECREF(o);
  554. return 0;
  555. }
  556. int
  557. PyModule_AddIntConstant(PyObject *m, const char *name, long value)
  558. {
  559. PyObject *o = PyInt_FromLong(value);
  560. if (!o)
  561. return -1;
  562. if (PyModule_AddObject(m, name, o) == 0)
  563. return 0;
  564. Py_DECREF(o);
  565. return -1;
  566. }
  567. int
  568. PyModule_AddStringConstant(PyObject *m, const char *name, const char *value)
  569. {
  570. PyObject *o = PyString_FromString(value);
  571. if (!o)
  572. return -1;
  573. if (PyModule_AddObject(m, name, o) == 0)
  574. return 0;
  575. Py_DECREF(o);
  576. return -1;
  577. }