Debian Codegraph @

c-ext/bufferutil.c

raw
1 /**
2 * Copyright (c) 2017-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 #include "python-zstandard.h"
10
11 extern PyObject *ZstdError;
12
13 static void BufferWithSegments_dealloc(ZstdBufferWithSegments *self) {
14 /* Backing memory is either canonically owned by a Py_buffer or by us. */
15 if (self->parent.buf) {
16 PyBuffer_Release(&self->parent);
17 }
18 else if (self->useFree) {
19 free(self->data);
20 }
21 else {
22 PyMem_Free(self->data);
23 }
24
25 self->data = NULL;
26
27 if (self->useFree) {
28 free(self->segments);
29 }
30 else {
31 PyMem_Free(self->segments);
32 }
33
34 self->segments = NULL;
35
36 PyObject_Del(self);
37 }
38
39 static int BufferWithSegments_init(ZstdBufferWithSegments *self, PyObject *args,
40 PyObject *kwargs) {
41 static char *kwlist[] = {"data", "segments", NULL};
42
43 Py_buffer segments;
44 Py_ssize_t segmentCount;
45 Py_ssize_t i;
46
47 memset(&self->parent, 0, sizeof(self->parent));
48
49 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*y*:BufferWithSegments",
50 kwlist, &self->parent, &segments)) {
51 return -1;
52 }
53
54 if (segments.len % sizeof(BufferSegment)) {
55 PyErr_Format(PyExc_ValueError,
56 "segments array size is not a multiple of %zu",
57 sizeof(BufferSegment));
58 goto except;
59 }
60
61 segmentCount = segments.len / sizeof(BufferSegment);
62
63 /* Validate segments data, as blindly trusting it could lead to arbitrary
64 memory access. */
65 for (i = 0; i < segmentCount; i++) {
66 BufferSegment *segment = &((BufferSegment *)(segments.buf))[i];
67
68 if (segment->offset + segment->length >
69 (unsigned long long)self->parent.len) {
70 PyErr_SetString(PyExc_ValueError,
71 "offset within segments array references memory "
72 "outside buffer");
73 goto except;
74 return -1;
75 }
76 }
77
78 /* Make a copy of the segments data. It is cheap to do so and is a guard
79 against caller changing offsets, which has security implications. */
80 self->segments = PyMem_Malloc(segments.len);
81 if (!self->segments) {
82 PyErr_NoMemory();
83 goto except;
84 }
85
86 memcpy(self->segments, segments.buf, segments.len);
87 PyBuffer_Release(&segments);
88
89 self->data = self->parent.buf;
90 self->dataSize = self->parent.len;
91 self->segmentCount = segmentCount;
92
93 return 0;
94
95 except:
96 PyBuffer_Release(&self->parent);
97 PyBuffer_Release(&segments);
98 return -1;
99 }
100
101 /**
102 * Construct a BufferWithSegments from existing memory and offsets.
103 *
104 * Ownership of the backing memory and BufferSegments will be transferred to
105 * the created object and freed when the BufferWithSegments is destroyed.
106 */
107 ZstdBufferWithSegments *
108 BufferWithSegments_FromMemory(void *data, unsigned long long dataSize,
109 BufferSegment *segments,
110 Py_ssize_t segmentsSize) {
111 ZstdBufferWithSegments *result = NULL;
112 Py_ssize_t i;
113
114 if (NULL == data) {
115 PyErr_SetString(PyExc_ValueError, "data is NULL");
116 return NULL;
117 }
118
119 if (NULL == segments) {
120 PyErr_SetString(PyExc_ValueError, "segments is NULL");
121 return NULL;
122 }
123
124 for (i = 0; i < segmentsSize; i++) {
125 BufferSegment *segment = &segments[i];
126
127 if (segment->offset + segment->length > dataSize) {
128 PyErr_SetString(PyExc_ValueError,
129 "offset in segments overflows buffer size");
130 return NULL;
131 }
132 }
133
134 result = PyObject_New(ZstdBufferWithSegments, ZstdBufferWithSegmentsType);
135 if (NULL == result) {
136 return NULL;
137 }
138
139 result->useFree = 0;
140
141 memset(&result->parent, 0, sizeof(result->parent));
142 result->data = data;
143 result->dataSize = dataSize;
144 result->segments = segments;
145 result->segmentCount = segmentsSize;
146
147 return result;
148 }
149
150 static Py_ssize_t BufferWithSegments_length(ZstdBufferWithSegments *self) {
151 return self->segmentCount;
152 }
153
154 static ZstdBufferSegment *BufferWithSegments_item(ZstdBufferWithSegments *self,
155 Py_ssize_t i) {
156 ZstdBufferSegment *result = NULL;
157
158 if (i < 0) {
159 PyErr_SetString(PyExc_IndexError, "offset must be non-negative");
160 return NULL;
161 }
162
163 if (i >= self->segmentCount) {
164 PyErr_Format(PyExc_IndexError, "offset must be less than %zd",
165 self->segmentCount);
166 return NULL;
167 }
168
169 if (self->segments[i].length > PY_SSIZE_T_MAX) {
170 PyErr_Format(PyExc_ValueError,
171 "item at offset %zd is too large for this platform", i);
172 return NULL;
173 }
174
175 result = (ZstdBufferSegment *)PyObject_CallObject(
176 (PyObject *)ZstdBufferSegmentType, NULL);
177 if (NULL == result) {
178 return NULL;
179 }
180
181 result->parent = (PyObject *)self;
182 Py_INCREF(self);
183
184 result->data = (char *)self->data + self->segments[i].offset;
185 result->dataSize = (Py_ssize_t)self->segments[i].length;
186 result->offset = self->segments[i].offset;
187
188 return result;
189 }
190
191 static int BufferWithSegments_getbuffer(ZstdBufferWithSegments *self,
192 Py_buffer *view, int flags) {
193 if (self->dataSize > PY_SSIZE_T_MAX) {
194 view->obj = NULL;
195 PyErr_SetString(PyExc_BufferError,
196 "buffer is too large for this platform");
197 return -1;
198 }
199
200 return PyBuffer_FillInfo(view, (PyObject *)self, self->data,
201 (Py_ssize_t)self->dataSize, 1, flags);
202 }
203
204 static PyObject *BufferWithSegments_tobytes(ZstdBufferWithSegments *self) {
205 if (self->dataSize > PY_SSIZE_T_MAX) {
206 PyErr_SetString(PyExc_ValueError,
207 "buffer is too large for this platform");
208 return NULL;
209 }
210
211 return PyBytes_FromStringAndSize(self->data, (Py_ssize_t)self->dataSize);
212 }
213
214 static ZstdBufferSegments *
215 BufferWithSegments_segments(ZstdBufferWithSegments *self) {
216 ZstdBufferSegments *result = (ZstdBufferSegments *)PyObject_CallObject(
217 (PyObject *)ZstdBufferSegmentsType, NULL);
218 if (NULL == result) {
219 return NULL;
220 }
221
222 result->parent = (PyObject *)self;
223 Py_INCREF(self);
224 result->segments = self->segments;
225 result->segmentCount = self->segmentCount;
226
227 return result;
228 }
229
230 #if PY_VERSION_HEX < 0x03090000
231 static PyBufferProcs BufferWithSegments_as_buffer = {
232 (getbufferproc)BufferWithSegments_getbuffer, /* bf_getbuffer */
233 0 /* bf_releasebuffer */
234 };
235 #endif
236
237 static PyMethodDef BufferWithSegments_methods[] = {
238 {"segments", (PyCFunction)BufferWithSegments_segments, METH_NOARGS, NULL},
239 {"tobytes", (PyCFunction)BufferWithSegments_tobytes, METH_NOARGS, NULL},
240 {NULL, NULL}};
241
242 static PyMemberDef BufferWithSegments_members[] = {
243 {"size", T_ULONGLONG, offsetof(ZstdBufferWithSegments, dataSize), READONLY,
244 "total size of the buffer in bytes"},
245 {NULL}};
246
247 PyType_Slot ZstdBufferWithSegmentsSlots[] = {
248 {Py_tp_dealloc, BufferWithSegments_dealloc},
249 {Py_sq_length, BufferWithSegments_length},
250 {Py_sq_item, BufferWithSegments_item},
251 #if PY_VERSION_HEX >= 0x03090000
252 {Py_bf_getbuffer, BufferWithSegments_getbuffer},
253 #endif
254 {Py_tp_methods, BufferWithSegments_methods},
255 {Py_tp_members, BufferWithSegments_members},
256 {Py_tp_init, BufferWithSegments_init},
257 {Py_tp_new, PyType_GenericNew},
258 {0, NULL},
259 };
260
261 PyType_Spec ZstdBufferWithSegmentsSpec = {
262 "zstandard.backend_c.BufferWithSegments",
263 sizeof(ZstdBufferWithSegments),
264 0,
265 Py_TPFLAGS_DEFAULT,
266 ZstdBufferWithSegmentsSlots,
267 };
268
269 PyTypeObject *ZstdBufferWithSegmentsType;
270
271 static void BufferSegments_dealloc(ZstdBufferSegments *self) {
272 Py_CLEAR(self->parent);
273 PyObject_Del(self);
274 }
275
276 static int BufferSegments_getbuffer(ZstdBufferSegments *self, Py_buffer *view,
277 int flags) {
278 return PyBuffer_FillInfo(view, (PyObject *)self, (void *)self->segments,
279 self->segmentCount * sizeof(BufferSegment), 1,
280 flags);
281 }
282
283 PyType_Slot ZstdBufferSegmentsSlots[] = {
284 {Py_tp_dealloc, BufferSegments_dealloc},
285 #if PY_VERSION_HEX >= 0x03090000
286 {Py_bf_getbuffer, BufferSegments_getbuffer},
287 #endif
288 {Py_tp_new, PyType_GenericNew},
289 {0, NULL},
290 };
291
292 PyType_Spec ZstdBufferSegmentsSpec = {
293 "zstandard.backend_c.BufferSegments",
294 sizeof(ZstdBufferSegments),
295 0,
296 Py_TPFLAGS_DEFAULT,
297 ZstdBufferSegmentsSlots,
298 };
299
300 #if PY_VERSION_HEX < 0x03090000
301 static PyBufferProcs BufferSegments_as_buffer = {
302 (getbufferproc)BufferSegments_getbuffer, 0};
303 #endif
304
305 PyTypeObject *ZstdBufferSegmentsType;
306
307 static void BufferSegment_dealloc(ZstdBufferSegment *self) {
308 Py_CLEAR(self->parent);
309 PyObject_Del(self);
310 }
311
312 static Py_ssize_t BufferSegment_length(ZstdBufferSegment *self) {
313 return self->dataSize;
314 }
315
316 static int BufferSegment_getbuffer(ZstdBufferSegment *self, Py_buffer *view,
317 int flags) {
318 return PyBuffer_FillInfo(view, (PyObject *)self, self->data, self->dataSize,
319 1, flags);
320 }
321
322 static PyObject *BufferSegment_tobytes(ZstdBufferSegment *self) {
323 return PyBytes_FromStringAndSize(self->data, self->dataSize);
324 }
325
326 #if PY_VERSION_HEX < 0x03090000
327 static PyBufferProcs BufferSegment_as_buffer = {
328 (getbufferproc)BufferSegment_getbuffer, 0};
329 #endif
330
331 static PyMethodDef BufferSegment_methods[] = {
332 {"tobytes", (PyCFunction)BufferSegment_tobytes, METH_NOARGS, NULL},
333 {NULL, NULL}};
334
335 static PyMemberDef BufferSegment_members[] = {
336 {"offset", T_ULONGLONG, offsetof(ZstdBufferSegment, offset), READONLY,
337 "offset of segment within parent buffer"},
338 {NULL}};
339
340 PyType_Slot ZstdBufferSegmentSlots[] = {
341 {Py_tp_dealloc, BufferSegment_dealloc},
342 {Py_sq_length, BufferSegment_length},
343 #if PY_VERSION_HEX >= 0x03090000
344 {Py_bf_getbuffer, BufferSegment_getbuffer},
345 #endif
346 {Py_tp_methods, BufferSegment_methods},
347 {Py_tp_members, BufferSegment_members},
348 {Py_tp_new, PyType_GenericNew},
349 {0, NULL},
350 };
351
352 PyType_Spec ZstdBufferSegmentSpec = {
353 "zstandard.backend_c.BufferSegment",
354 sizeof(ZstdBufferSegment),
355 0,
356 Py_TPFLAGS_DEFAULT,
357 ZstdBufferSegmentSlots,
358 };
359
360 PyTypeObject *ZstdBufferSegmentType;
361
362 static void
363 BufferWithSegmentsCollection_dealloc(ZstdBufferWithSegmentsCollection *self) {
364 Py_ssize_t i;
365
366 if (self->firstElements) {
367 PyMem_Free(self->firstElements);
368 self->firstElements = NULL;
369 }
370
371 if (self->buffers) {
372 for (i = 0; i < self->bufferCount; i++) {
373 Py_CLEAR(self->buffers[i]);
374 }
375
376 PyMem_Free(self->buffers);
377 self->buffers = NULL;
378 }
379
380 PyObject_Del(self);
381 }
382
383 static int
384 BufferWithSegmentsCollection_init(ZstdBufferWithSegmentsCollection *self,
385 PyObject *args) {
386 Py_ssize_t size;
387 Py_ssize_t i;
388 Py_ssize_t offset = 0;
389
390 size = PyTuple_Size(args);
391 if (-1 == size) {
392 return -1;
393 }
394
395 if (0 == size) {
396 PyErr_SetString(PyExc_ValueError, "must pass at least 1 argument");
397 return -1;
398 }
399
400 for (i = 0; i < size; i++) {
401 PyObject *item = PyTuple_GET_ITEM(args, i);
402 if (!PyObject_TypeCheck(item, ZstdBufferWithSegmentsType)) {
403 PyErr_SetString(PyExc_TypeError,
404 "arguments must be BufferWithSegments instances");
405 return -1;
406 }
407
408 if (0 == ((ZstdBufferWithSegments *)item)->segmentCount ||
409 0 == ((ZstdBufferWithSegments *)item)->dataSize) {
410 PyErr_SetString(PyExc_ValueError,
411 "ZstdBufferWithSegments cannot be empty");
412 return -1;
413 }
414 }
415
416 self->buffers = PyMem_Malloc(size * sizeof(ZstdBufferWithSegments *));
417 if (NULL == self->buffers) {
418 PyErr_NoMemory();
419 return -1;
420 }
421
422 self->firstElements = PyMem_Malloc(size * sizeof(Py_ssize_t));
423 if (NULL == self->firstElements) {
424 PyMem_Free(self->buffers);
425 self->buffers = NULL;
426 PyErr_NoMemory();
427 return -1;
428 }
429
430 self->bufferCount = size;
431
432 for (i = 0; i < size; i++) {
433 ZstdBufferWithSegments *item =
434 (ZstdBufferWithSegments *)PyTuple_GET_ITEM(args, i);
435
436 self->buffers[i] = item;
437 Py_INCREF(item);
438
439 if (i > 0) {
440 self->firstElements[i - 1] = offset;
441 }
442
443 offset += item->segmentCount;
444 }
445
446 self->firstElements[size - 1] = offset;
447
448 return 0;
449 }
450
451 static PyObject *
452 BufferWithSegmentsCollection_size(ZstdBufferWithSegmentsCollection *self) {
453 Py_ssize_t i;
454 Py_ssize_t j;
455 unsigned long long size = 0;
456
457 for (i = 0; i < self->bufferCount; i++) {
458 for (j = 0; j < self->buffers[i]->segmentCount; j++) {
459 size += self->buffers[i]->segments[j].length;
460 }
461 }
462
463 return PyLong_FromUnsignedLongLong(size);
464 }
465
466 Py_ssize_t
467 BufferWithSegmentsCollection_length(ZstdBufferWithSegmentsCollection *self) {
468 return self->firstElements[self->bufferCount - 1];
469 }
470
471 static ZstdBufferSegment *
472 BufferWithSegmentsCollection_item(ZstdBufferWithSegmentsCollection *self,
473 Py_ssize_t i) {
474 Py_ssize_t bufferOffset;
475
476 if (i < 0) {
477 PyErr_SetString(PyExc_IndexError, "offset must be non-negative");
478 return NULL;
479 }
480
481 if (i >= BufferWithSegmentsCollection_length(self)) {
482 PyErr_Format(PyExc_IndexError, "offset must be less than %zd",
483 BufferWithSegmentsCollection_length(self));
484 return NULL;
485 }
486
487 for (bufferOffset = 0; bufferOffset < self->bufferCount; bufferOffset++) {
488 Py_ssize_t offset = 0;
489
490 if (i < self->firstElements[bufferOffset]) {
491 if (bufferOffset > 0) {
492 offset = self->firstElements[bufferOffset - 1];
493 }
494
495 return BufferWithSegments_item(self->buffers[bufferOffset],
496 i - offset);
497 }
498 }
499
500 PyErr_SetString(ZstdError,
501 "error resolving segment; this should not happen");
502 return NULL;
503 }
504
505 static PyMethodDef BufferWithSegmentsCollection_methods[] = {
506 {"size", (PyCFunction)BufferWithSegmentsCollection_size, METH_NOARGS,
507 PyDoc_STR("total size in bytes of all segments")},
508 {NULL, NULL}};
509
510 PyType_Slot ZstdBufferWithSegmentsCollectionSlots[] = {
511 {Py_tp_dealloc, BufferWithSegmentsCollection_dealloc},
512 {Py_sq_length, BufferWithSegmentsCollection_length},
513 {Py_sq_item, BufferWithSegmentsCollection_item},
514 {Py_tp_methods, BufferWithSegmentsCollection_methods},
515 {Py_tp_init, BufferWithSegmentsCollection_init},
516 {Py_tp_new, PyType_GenericNew},
517 {0, NULL},
518 };
519
520 PyType_Spec ZstdBufferWithSegmentsCollectionSpec = {
521 "zstandard.backend_c.BufferWithSegmentsCollection",
522 sizeof(ZstdBufferWithSegmentsCollection),
523 0,
524 Py_TPFLAGS_DEFAULT,
525 ZstdBufferWithSegmentsCollectionSlots,
526 };
527
528 PyTypeObject *ZstdBufferWithSegmentsCollectionType;
529
530 void bufferutil_module_init(PyObject *mod) {
531 ZstdBufferWithSegmentsType =
532 (PyTypeObject *)PyType_FromSpec(&ZstdBufferWithSegmentsSpec);
533 #if PY_VERSION_HEX < 0x03090000
534 ZstdBufferWithSegmentsType->tp_as_buffer = &BufferWithSegments_as_buffer;
535 #endif
536 if (PyType_Ready(ZstdBufferWithSegmentsType) < 0) {
537 return;
538 }
539
540 Py_INCREF(ZstdBufferWithSegmentsType);
541 PyModule_AddObject(mod, "BufferWithSegments",
542 (PyObject *)ZstdBufferWithSegmentsType);
543
544 ZstdBufferSegmentsType =
545 (PyTypeObject *)PyType_FromSpec(&ZstdBufferSegmentsSpec);
546 #if PY_VERSION_HEX < 0x03090000
547 ZstdBufferSegmentsType->tp_as_buffer = &BufferSegments_as_buffer;
548 #endif
549 if (PyType_Ready(ZstdBufferSegmentsType) < 0) {
550 return;
551 }
552
553 Py_INCREF(ZstdBufferSegmentsType);
554 PyModule_AddObject(mod, "BufferSegments",
555 (PyObject *)ZstdBufferSegmentsType);
556
557 ZstdBufferSegmentType =
558 (PyTypeObject *)PyType_FromSpec(&ZstdBufferSegmentSpec);
559 #if PY_VERSION_HEX < 0x03090000
560 ZstdBufferSegmentType->tp_as_buffer = &BufferSegment_as_buffer;
561 #endif
562 if (PyType_Ready(ZstdBufferSegmentType) < 0) {
563 return;
564 }
565
566 Py_INCREF(ZstdBufferSegmentType);
567 PyModule_AddObject(mod, "BufferSegment", (PyObject *)ZstdBufferSegmentType);
568
569 ZstdBufferWithSegmentsCollectionType =
570 (PyTypeObject *)PyType_FromSpec(&ZstdBufferWithSegmentsCollectionSpec);
571 if (PyType_Ready(ZstdBufferWithSegmentsCollectionType) < 0) {
572 return;
573 }
574
575 Py_INCREF(ZstdBufferWithSegmentsCollectionType);
576 PyModule_AddObject(mod, "BufferWithSegmentsCollection",
577 (PyObject *)ZstdBufferWithSegmentsCollectionType);
578 }