You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
2.7 KiB

  1. /* Support for dynamic loading of extension modules */
  2. #include "Python.h"
  3. /* ./configure sets HAVE_DYNAMIC_LOADING if dynamic loading of modules is
  4. supported on this platform. configure will then compile and link in one
  5. of the dynload_*.c files, as appropriate. We will call a function in
  6. those modules to get a function pointer to the module's init function.
  7. */
  8. #ifdef HAVE_DYNAMIC_LOADING
  9. #include "importdl.h"
  10. extern dl_funcptr _PyImport_GetDynLoadFunc(const char *name,
  11. const char *shortname,
  12. const char *pathname, FILE *fp);
  13. PyObject *
  14. _PyImport_LoadDynamicModule(char *name, char *pathname, FILE *fp)
  15. {
  16. PyObject *m;
  17. PyObject *path;
  18. char *lastdot, *shortname, *packagecontext, *oldcontext;
  19. dl_funcptr p0;
  20. PyObject* (*p)(void);
  21. struct PyModuleDef *def;
  22. PyObject *result;
  23. path = PyUnicode_DecodeFSDefault(pathname);
  24. if (path == NULL)
  25. return NULL;
  26. if ((m = _PyImport_FindExtensionUnicode(name, path)) != NULL) {
  27. Py_INCREF(m);
  28. result = m;
  29. goto finally;
  30. }
  31. lastdot = strrchr(name, '.');
  32. if (lastdot == NULL) {
  33. packagecontext = NULL;
  34. shortname = name;
  35. }
  36. else {
  37. packagecontext = name;
  38. shortname = lastdot+1;
  39. }
  40. p0 = _PyImport_GetDynLoadFunc(name, shortname, pathname, fp);
  41. p = (PyObject*(*)(void))p0;
  42. if (PyErr_Occurred())
  43. goto error;
  44. if (p == NULL) {
  45. PyErr_Format(PyExc_ImportError,
  46. "dynamic module does not define init function (PyInit_%.200s)",
  47. shortname);
  48. goto error;
  49. }
  50. oldcontext = _Py_PackageContext;
  51. _Py_PackageContext = packagecontext;
  52. m = (*p)();
  53. _Py_PackageContext = oldcontext;
  54. if (m == NULL)
  55. goto error;
  56. if (PyErr_Occurred()) {
  57. Py_DECREF(m);
  58. PyErr_Format(PyExc_SystemError,
  59. "initialization of %s raised unreported exception",
  60. shortname);
  61. goto error;
  62. }
  63. /* Remember pointer to module init function. */
  64. def = PyModule_GetDef(m);
  65. def->m_base.m_init = p;
  66. /* Remember the filename as the __file__ attribute */
  67. if (PyModule_AddObject(m, "__file__", path) < 0)
  68. PyErr_Clear(); /* Not important enough to report */
  69. else
  70. Py_INCREF(path);
  71. if (_PyImport_FixupExtensionUnicode(m, name, path) < 0)
  72. goto error;
  73. if (Py_VerboseFlag)
  74. PySys_WriteStderr(
  75. "import %s # dynamically loaded from %s\n",
  76. name, pathname);
  77. result = m;
  78. goto finally;
  79. error:
  80. result = NULL;
  81. finally:
  82. Py_DECREF(path);
  83. return result;
  84. }
  85. #endif /* HAVE_DYNAMIC_LOADING */