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.

61 lines
2.1 KiB

  1. /* Common code for use by all hashlib related modules. */
  2. /*
  3. * Given a PyObject* obj, fill in the Py_buffer* viewp with the result
  4. * of PyObject_GetBuffer. Sets an exception and issues a return NULL
  5. * on any errors.
  6. */
  7. #define GET_BUFFER_VIEW_OR_ERROUT(obj, viewp) do { \
  8. if (PyUnicode_Check((obj))) { \
  9. PyErr_SetString(PyExc_TypeError, \
  10. "Unicode-objects must be encoded before hashing");\
  11. return NULL; \
  12. } \
  13. if (!PyObject_CheckBuffer((obj))) { \
  14. PyErr_SetString(PyExc_TypeError, \
  15. "object supporting the buffer API required"); \
  16. return NULL; \
  17. } \
  18. if (PyObject_GetBuffer((obj), (viewp), PyBUF_SIMPLE) == -1) { \
  19. return NULL; \
  20. } \
  21. if ((viewp)->ndim > 1) { \
  22. PyErr_SetString(PyExc_BufferError, \
  23. "Buffer must be single dimension"); \
  24. PyBuffer_Release((viewp)); \
  25. return NULL; \
  26. } \
  27. } while(0);
  28. /*
  29. * Helper code to synchronize access to the hash object when the GIL is
  30. * released around a CPU consuming hashlib operation. All code paths that
  31. * access a mutable part of obj must be enclosed in an ENTER_HASHLIB /
  32. * LEAVE_HASHLIB block or explicitly acquire and release the lock inside
  33. * a PY_BEGIN / END_ALLOW_THREADS block if they wish to release the GIL for
  34. * an operation.
  35. */
  36. #ifdef WITH_THREAD
  37. #include "pythread.h"
  38. #define ENTER_HASHLIB(obj) \
  39. if ((obj)->lock) { \
  40. if (!PyThread_acquire_lock((obj)->lock, 0)) { \
  41. Py_BEGIN_ALLOW_THREADS \
  42. PyThread_acquire_lock((obj)->lock, 1); \
  43. Py_END_ALLOW_THREADS \
  44. } \
  45. }
  46. #define LEAVE_HASHLIB(obj) \
  47. if ((obj)->lock) { \
  48. PyThread_release_lock((obj)->lock); \
  49. }
  50. #else
  51. #define ENTER_HASHLIB(obj)
  52. #define LEAVE_HASHLIB(obj)
  53. #endif
  54. /* TODO(gps): We should probably make this a module or EVPobject attribute
  55. * to allow the user to optimize based on the platform they're using. */
  56. #define HASHLIB_GIL_MINSIZE 2048