blob: 530b6b1723cef0dd30368ecfdffe52d2bc97d4ab [file] [log] [blame]
Gregory P. Smith365a1862009-02-12 07:35:29 +00001/* Common code for use by all hashlib related modules. */
2
3/*
4 * Given a PyObject* obj, fill in the Py_buffer* viewp with the result
Christian Heimes121b9482016-09-06 22:03:25 +02005 * of PyObject_GetBuffer. Sets an exception and issues the erraction
6 * on any errors, e.g. 'return NULL' or 'goto error'.
Gregory P. Smith365a1862009-02-12 07:35:29 +00007 */
Christian Heimes121b9482016-09-06 22:03:25 +02008#define GET_BUFFER_VIEW_OR_ERROR(obj, viewp, erraction) do { \
Gregory P. Smith365a1862009-02-12 07:35:29 +00009 if (PyUnicode_Check((obj))) { \
10 PyErr_SetString(PyExc_TypeError, \
11 "Unicode-objects must be encoded before hashing");\
Christian Heimes121b9482016-09-06 22:03:25 +020012 erraction; \
Gregory P. Smith365a1862009-02-12 07:35:29 +000013 } \
14 if (!PyObject_CheckBuffer((obj))) { \
15 PyErr_SetString(PyExc_TypeError, \
16 "object supporting the buffer API required"); \
Christian Heimes121b9482016-09-06 22:03:25 +020017 erraction; \
Gregory P. Smith365a1862009-02-12 07:35:29 +000018 } \
19 if (PyObject_GetBuffer((obj), (viewp), PyBUF_SIMPLE) == -1) { \
Christian Heimes121b9482016-09-06 22:03:25 +020020 erraction; \
Gregory P. Smith365a1862009-02-12 07:35:29 +000021 } \
22 if ((viewp)->ndim > 1) { \
23 PyErr_SetString(PyExc_BufferError, \
24 "Buffer must be single dimension"); \
25 PyBuffer_Release((viewp)); \
Christian Heimes121b9482016-09-06 22:03:25 +020026 erraction; \
Gregory P. Smith365a1862009-02-12 07:35:29 +000027 } \
Christian Heimes121b9482016-09-06 22:03:25 +020028 } while(0)
29
30#define GET_BUFFER_VIEW_OR_ERROUT(obj, viewp) \
31 GET_BUFFER_VIEW_OR_ERROR(obj, viewp, return NULL)
Christian Heimes4a0270d2012-10-06 02:23:36 +020032
33/*
34 * Helper code to synchronize access to the hash object when the GIL is
35 * released around a CPU consuming hashlib operation. All code paths that
Martin Panter7462b6492015-11-02 03:37:02 +000036 * access a mutable part of obj must be enclosed in an ENTER_HASHLIB /
Christian Heimes4a0270d2012-10-06 02:23:36 +020037 * LEAVE_HASHLIB block or explicitly acquire and release the lock inside
38 * a PY_BEGIN / END_ALLOW_THREADS block if they wish to release the GIL for
39 * an operation.
40 */
41
42#ifdef WITH_THREAD
43#include "pythread.h"
44 #define ENTER_HASHLIB(obj) \
45 if ((obj)->lock) { \
46 if (!PyThread_acquire_lock((obj)->lock, 0)) { \
47 Py_BEGIN_ALLOW_THREADS \
48 PyThread_acquire_lock((obj)->lock, 1); \
49 Py_END_ALLOW_THREADS \
50 } \
51 }
52 #define LEAVE_HASHLIB(obj) \
53 if ((obj)->lock) { \
54 PyThread_release_lock((obj)->lock); \
55 }
56#else
57 #define ENTER_HASHLIB(obj)
58 #define LEAVE_HASHLIB(obj)
59#endif
60
61/* TODO(gps): We should probably make this a module or EVPobject attribute
62 * to allow the user to optimize based on the platform they're using. */
63#define HASHLIB_GIL_MINSIZE 2048
64