Debian Codegraph @

contrib/python-zstandard/c-ext/backend_c.c

raw
1 /**
2 * Copyright (c) 2016-present, Gregory Szorc
3 * All rights reserved.
4 *
5 * This software may be modified and distributed under the terms
6 * of the BSD license. See the LICENSE file for details.
7 */
8
9 /* A Python C extension for Zstandard. */
10
11 #if defined(_WIN32)
12 #define WIN32_LEAN_AND_MEAN
13 #include <Windows.h>
14 #elif defined(__APPLE__) || defined(__OpenBSD__) || defined(__FreeBSD__) || \
15 defined(__NetBSD__) || defined(__DragonFly__)
16 #include <sys/types.h>
17
18 #include <sys/sysctl.h>
19
20 #endif
21
22 #include "python-zstandard.h"
23
24 #include "bufferutil.c"
25 #include "compressionchunker.c"
26 #include "compressiondict.c"
27 #include "compressionparams.c"
28 #include "compressionreader.c"
29 #include "compressionwriter.c"
30 #include "compressobj.c"
31 #include "compressor.c"
32 #include "compressoriterator.c"
33 #include "constants.c"
34 #include "decompressionreader.c"
35 #include "decompressionwriter.c"
36 #include "decompressobj.c"
37 #include "decompressor.c"
38 #include "decompressoriterator.c"
39 #include "frameparams.c"
40
41 PyObject *ZstdError;
42
43 static PyObject *estimate_decompression_context_size(PyObject *self) {
44 return PyLong_FromSize_t(ZSTD_estimateDCtxSize());
45 }
46
47 static PyObject *frame_content_size(PyObject *self, PyObject *args,
48 PyObject *kwargs) {
49 static char *kwlist[] = {"source", NULL};
50
51 Py_buffer source;
52 PyObject *result = NULL;
53 unsigned long long size;
54
55 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*:frame_content_size",
56 kwlist, &source)) {
57 return NULL;
58 }
59
60 size = ZSTD_getFrameContentSize(source.buf, source.len);
61
62 if (size == ZSTD_CONTENTSIZE_ERROR) {
63 PyErr_SetString(ZstdError, "error when determining content size");
64 }
65 else if (size == ZSTD_CONTENTSIZE_UNKNOWN) {
66 result = PyLong_FromLong(-1);
67 }
68 else {
69 result = PyLong_FromUnsignedLongLong(size);
70 }
71
72 PyBuffer_Release(&source);
73
74 return result;
75 }
76
77 static PyObject *frame_header_size(PyObject *self, PyObject *args,
78 PyObject *kwargs) {
79 static char *kwlist[] = {"source", NULL};
80
81 Py_buffer source;
82 PyObject *result = NULL;
83 size_t zresult;
84
85 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*:frame_header_size",
86 kwlist, &source)) {
87 return NULL;
88 }
89
90 zresult = ZSTD_frameHeaderSize(source.buf, source.len);
91 if (ZSTD_isError(zresult)) {
92 PyErr_Format(ZstdError, "could not determine frame header size: %s",
93 ZSTD_getErrorName(zresult));
94 }
95 else {
96 result = PyLong_FromSize_t(zresult);
97 }
98
99 PyBuffer_Release(&source);
100
101 return result;
102 }
103
104 static char zstd_doc[] = "Interface to zstandard";
105
106 static PyMethodDef zstd_methods[] = {
107 {"estimate_decompression_context_size",
108 (PyCFunction)estimate_decompression_context_size, METH_NOARGS, NULL},
109 {"frame_content_size", (PyCFunction)frame_content_size,
110 METH_VARARGS | METH_KEYWORDS, NULL},
111 {"frame_header_size", (PyCFunction)frame_header_size,
112 METH_VARARGS | METH_KEYWORDS, NULL},
113 {"get_frame_parameters", (PyCFunction)get_frame_parameters,
114 METH_VARARGS | METH_KEYWORDS, NULL},
115 {"train_dictionary", (PyCFunction)train_dictionary,
116 METH_VARARGS | METH_KEYWORDS, NULL},
117 {NULL, NULL}};
118
119 void bufferutil_module_init(PyObject *mod);
120 void compressobj_module_init(PyObject *mod);
121 void compressor_module_init(PyObject *mod);
122 void compressionparams_module_init(PyObject *mod);
123 void constants_module_init(PyObject *mod);
124 void compressionchunker_module_init(PyObject *mod);
125 void compressiondict_module_init(PyObject *mod);
126 void compressionreader_module_init(PyObject *mod);
127 void compressionwriter_module_init(PyObject *mod);
128 void compressoriterator_module_init(PyObject *mod);
129 void decompressor_module_init(PyObject *mod);
130 void decompressobj_module_init(PyObject *mod);
131 void decompressionreader_module_init(PyObject *mod);
132 void decompressionwriter_module_init(PyObject *mod);
133 void decompressoriterator_module_init(PyObject *mod);
134 void frameparams_module_init(PyObject *mod);
135
136 void zstd_module_init(PyObject *m) {
137 /* python-zstandard relies on unstable zstd C API features. This means
138 that changes in zstd may break expectations in python-zstandard.
139
140 python-zstandard is distributed with a copy of the zstd sources.
141 python-zstandard is only guaranteed to work with the bundled version
142 of zstd.
143
144 However, downstream redistributors or packagers may unbundle zstd
145 from python-zstandard. This can result in a mismatch between zstd
146 versions and API semantics. This essentially "voids the warranty"
147 of python-zstandard and may cause undefined behavior.
148
149 We detect this mismatch here and refuse to load the module if this
150 scenario is detected.
151 */
152 PyObject *features = NULL;
153 PyObject *feature = NULL;
154 unsigned zstd_ver_no = ZSTD_versionNumber();
155 unsigned our_hardcoded_version = 10506;
156 if (ZSTD_VERSION_NUMBER != our_hardcoded_version ||
157 zstd_ver_no != our_hardcoded_version) {
158 PyErr_Format(
159 PyExc_ImportError,
160 "zstd C API versions mismatch; Python bindings were not "
161 "compiled/linked against expected zstd version (%u returned by the "
162 "lib, %u hardcoded in zstd headers, %u hardcoded in the cext)",
163 zstd_ver_no, ZSTD_VERSION_NUMBER, our_hardcoded_version);
164 return;
165 }
166
167 features = PySet_New(NULL);
168 if (NULL == features) {
169 PyErr_SetString(PyExc_ImportError, "could not create empty set");
170 return;
171 }
172
173 feature = PyUnicode_FromString("buffer_types");
174 if (NULL == feature) {
175 PyErr_SetString(PyExc_ImportError, "could not create feature string");
176 return;
177 }
178
179 if (PySet_Add(features, feature) == -1) {
180 return;
181 }
182
183 Py_DECREF(feature);
184
185 #ifdef HAVE_ZSTD_POOL_APIS
186 feature = PyUnicode_FromString("multi_compress_to_buffer");
187 if (NULL == feature) {
188 PyErr_SetString(PyExc_ImportError, "could not create feature string");
189 return;
190 }
191
192 if (PySet_Add(features, feature) == -1) {
193 return;
194 }
195
196 Py_DECREF(feature);
197 #endif
198
199 #ifdef HAVE_ZSTD_POOL_APIS
200 feature = PyUnicode_FromString("multi_decompress_to_buffer");
201 if (NULL == feature) {
202 PyErr_SetString(PyExc_ImportError, "could not create feature string");
203 return;
204 }
205
206 if (PySet_Add(features, feature) == -1) {
207 return;
208 }
209
210 Py_DECREF(feature);
211 #endif
212
213 if (PyObject_SetAttrString(m, "backend_features", features) == -1) {
214 return;
215 }
216
217 Py_DECREF(features);
218
219 bufferutil_module_init(m);
220 compressionparams_module_init(m);
221 compressiondict_module_init(m);
222 compressobj_module_init(m);
223 compressor_module_init(m);
224 compressionchunker_module_init(m);
225 compressionreader_module_init(m);
226 compressionwriter_module_init(m);
227 compressoriterator_module_init(m);
228 constants_module_init(m);
229 decompressor_module_init(m);
230 decompressobj_module_init(m);
231 decompressionreader_module_init(m);
232 decompressionwriter_module_init(m);
233 decompressoriterator_module_init(m);
234 frameparams_module_init(m);
235 }
236
237 #if defined(__GNUC__) && (__GNUC__ >= 4)
238 #define PYTHON_ZSTD_VISIBILITY __attribute__((visibility("default")))
239 #else
240 #define PYTHON_ZSTD_VISIBILITY
241 #endif
242
243 static struct PyModuleDef zstd_module = {PyModuleDef_HEAD_INIT, "zstd",
244 zstd_doc, -1, zstd_methods};
245
246 PYTHON_ZSTD_VISIBILITY PyMODINIT_FUNC PyInit_zstd(void) {
247 PyObject *m = PyModule_Create(&zstd_module);
248 if (m) {
249 zstd_module_init(m);
250 if (PyErr_Occurred()) {
251 Py_DECREF(m);
252 m = NULL;
253 }
254 }
255 return m;
256 }
257
258 /* Attempt to resolve the number of CPUs in the system. */
259 int cpu_count() {
260 int count = 0;
261
262 #if defined(_WIN32)
263 SYSTEM_INFO si;
264 si.dwNumberOfProcessors = 0;
265 GetSystemInfo(&si);
266 count = si.dwNumberOfProcessors;
267 #elif defined(__APPLE__)
268 int num;
269 size_t size = sizeof(int);
270
271 if (0 == sysctlbyname("hw.logicalcpu", &num, &size, NULL, 0)) {
272 count = num;
273 }
274 #elif defined(__linux__)
275 count = sysconf(_SC_NPROCESSORS_ONLN);
276 #elif defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
277 defined(__DragonFly__)
278 int mib[2];
279 size_t len = sizeof(count);
280 mib[0] = CTL_HW;
281 mib[1] = HW_NCPU;
282 if (0 != sysctl(mib, 2, &count, &len, NULL, 0)) {
283 count = 0;
284 }
285 #elif defined(__hpux)
286 count = mpctl(MPC_GETNUMSPUS, NULL, NULL);
287 #endif
288
289 return count;
290 }
291
292 size_t roundpow2(size_t i) {
293 i--;
294 i |= i >> 1;
295 i |= i >> 2;
296 i |= i >> 4;
297 i |= i >> 8;
298 i |= i >> 16;
299 i++;
300
301 return i;
302 }
303
304 /* Safer version of _PyBytes_Resize().
305 *
306 * _PyBytes_Resize() only works if the refcount is 1. In some scenarios,
307 * we can get an object with a refcount > 1, even if it was just created
308 * with PyBytes_FromStringAndSize()! That's because (at least) CPython
309 * pre-allocates PyBytes instances of size 1 for every possible byte value.
310 *
311 * If non-0 is returned, obj may or may not be NULL.
312 */
313 int safe_pybytes_resize(PyObject **obj, Py_ssize_t size) {
314 PyObject *tmp;
315
316 if ((*obj)->ob_refcnt == 1) {
317 return _PyBytes_Resize(obj, size);
318 }
319
320 tmp = PyBytes_FromStringAndSize(NULL, size);
321 if (!tmp) {
322 return -1;
323 }
324
325 memcpy(PyBytes_AS_STRING(tmp), PyBytes_AS_STRING(*obj),
326 PyBytes_GET_SIZE(*obj));
327
328 Py_DECREF(*obj);
329 *obj = tmp;
330
331 return 0;
332 }
333
334 // Set/raise an `io.UnsupportedOperation` exception.
335 void set_io_unsupported_operation(void) {
336 PyObject *iomod;
337 PyObject *exc;
338
339 iomod = PyImport_ImportModule("io");
340 if (NULL == iomod) {
341 return;
342 }
343
344 exc = PyObject_GetAttrString(iomod, "UnsupportedOperation");
345 if (NULL == exc) {
346 Py_DECREF(iomod);
347 return;
348 }
349
350 PyErr_SetNone(exc);
351 Py_DECREF(exc);
352 Py_DECREF(iomod);
353 }