Debian Codegraph @

hgext/fsmonitor/pywatchman/bser.c

raw
1 /*
2 Copyright (c) 2013-2015, Facebook, Inc.
3 All rights reserved.
4
5 Redistribution and use in source and binary forms, with or without
6 modification, are permitted provided that the following conditions are met:
7
8 * Redistributions of source code must retain the above copyright notice,
9 this list of conditions and the following disclaimer.
10
11 * Redistributions in binary form must reproduce the above copyright notice,
12 this list of conditions and the following disclaimer in the documentation
13 and/or other materials provided with the distribution.
14
15 * Neither the name Facebook nor the names of its contributors may be used to
16 endorse or promote products derived from this software without specific
17 prior written permission.
18
19 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31 #define PY_SSIZE_T_CLEAN
32 #include <Python.h>
33 #include <bytesobject.h>
34 #ifdef _MSC_VER
35 #define inline __inline
36 #if _MSC_VER >= 1800
37 #include <stdint.h>
38 #else
39 // The compiler associated with Python 2.7 on Windows doesn't ship
40 // with stdint.h, so define the small subset that we use here.
41 typedef __int8 int8_t;
42 typedef __int16 int16_t;
43 typedef __int32 int32_t;
44 typedef __int64 int64_t;
45 typedef unsigned __int8 uint8_t;
46 typedef unsigned __int16 uint16_t;
47 typedef unsigned __int32 uint32_t;
48 typedef unsigned __int64 uint64_t;
49 #define UINT32_MAX 4294967295U
50 #endif
51 #endif
52
53 // clang-format off
54 /* Return the smallest size int that can store the value */
55 #define INT_SIZE(x) (((x) == ((int8_t)x)) ? 1 : \
56 ((x) == ((int16_t)x)) ? 2 : \
57 ((x) == ((int32_t)x)) ? 4 : 8)
58
59 #define BSER_ARRAY 0x00
60 #define BSER_OBJECT 0x01
61 #define BSER_BYTESTRING 0x02
62 #define BSER_INT8 0x03
63 #define BSER_INT16 0x04
64 #define BSER_INT32 0x05
65 #define BSER_INT64 0x06
66 #define BSER_REAL 0x07
67 #define BSER_TRUE 0x08
68 #define BSER_FALSE 0x09
69 #define BSER_NULL 0x0a
70 #define BSER_TEMPLATE 0x0b
71 #define BSER_SKIP 0x0c
72 #define BSER_UTF8STRING 0x0d
73 // clang-format on
74
75 // An immutable object representation of BSER_OBJECT.
76 // Rather than build a hash table, key -> value are obtained
77 // by walking the list of keys to determine the offset into
78 // the values array. The assumption is that the number of
79 // array elements will be typically small (~6 for the top
80 // level query result and typically 3-5 for the file entries)
81 // so that the time overhead for this is small compared to
82 // using a proper hash table. Even with this simplistic
83 // approach, this is still faster for the mercurial use case
84 // as it helps to eliminate creating N other objects to
85 // represent the stat information in the hgwatchman extension
86 // clang-format off
87 typedef struct {
88 PyObject_HEAD
89 PyObject *keys; // tuple of field names
90 PyObject *values; // tuple of values
91 } bserObject;
92 // clang-format on
93
94 static Py_ssize_t bserobj_tuple_length(PyObject* o) {
95 bserObject* obj = (bserObject*)o;
96
97 return PySequence_Length(obj->keys);
98 }
99
100 static PyObject* bserobj_tuple_item(PyObject* o, Py_ssize_t i) {
101 bserObject* obj = (bserObject*)o;
102
103 return PySequence_GetItem(obj->values, i);
104 }
105
106 // clang-format off
107 static PySequenceMethods bserobj_sq = {
108 bserobj_tuple_length, /* sq_length */
109 0, /* sq_concat */
110 0, /* sq_repeat */
111 bserobj_tuple_item, /* sq_item */
112 0, /* sq_ass_item */
113 0, /* sq_contains */
114 0, /* sq_inplace_concat */
115 0 /* sq_inplace_repeat */
116 };
117 // clang-format on
118
119 static void bserobj_dealloc(PyObject* o) {
120 bserObject* obj = (bserObject*)o;
121
122 Py_CLEAR(obj->keys);
123 Py_CLEAR(obj->values);
124 PyObject_Del(o);
125 }
126
127 static PyObject* bserobj_getattrro(PyObject* o, PyObject* name) {
128 bserObject* obj = (bserObject*)o;
129 Py_ssize_t i, n;
130 PyObject* name_bytes = NULL;
131 PyObject* ret = NULL;
132 const char* namestr = NULL;
133
134 if (PyIndex_Check(name)) {
135 i = PyNumber_AsSsize_t(name, PyExc_IndexError);
136 if (i == -1 && PyErr_Occurred()) {
137 goto bail;
138 }
139
140 if (i == 8 && PySequence_Size(obj->values) < 9) {
141 // Hack alert: Python 3 removed support for os.stat().st_mtime
142 // being an integer.Instead, if you need an integer, you have to
143 // use os.stat()[stat.ST_MTIME] instead. stat.ST_MTIME is 8, and
144 // our stat tuples are shorter than that, so we can detect
145 // requests for index 8 on tuples shorter than that and return
146 // st_mtime instead.
147 namestr = "st_mtime";
148 } else {
149 ret = PySequence_GetItem(obj->values, i);
150 goto bail;
151 }
152 } else {
153 // We can be passed in Unicode objects here -- we don't support anything other
154 // than UTF-8 for keys.
155 if (PyUnicode_Check(name)) {
156 name_bytes = PyUnicode_AsUTF8String(name);
157 if (name_bytes == NULL) {
158 goto bail;
159 }
160 namestr = PyBytes_AsString(name_bytes);
161 } else {
162 namestr = PyBytes_AsString(name);
163 }
164 }
165
166 if (namestr == NULL) {
167 goto bail;
168 }
169 // hack^Wfeature to allow mercurial to use "st_size" to reference "size"
170 if (!strncmp(namestr, "st_", 3)) {
171 namestr += 3;
172 }
173
174 n = PyTuple_GET_SIZE(obj->keys);
175 for (i = 0; i < n; i++) {
176 const char* item_name = NULL;
177 PyObject* key = PyTuple_GET_ITEM(obj->keys, i);
178
179 if (PyUnicode_Check(key)) {
180 #if PY_MAJOR_VERSION >= 3
181 item_name = PyUnicode_AsUTF8(key);
182 #else
183 PyObject* utf = PyUnicode_AsEncodedString(key, "utf-8", "ignore");
184 if (utf == NULL) {
185 goto bail;
186 }
187 item_name = PyBytes_AsString(utf);
188 #endif
189 } else {
190 item_name = PyBytes_AsString(key);
191 }
192 if (item_name == NULL) {
193 goto bail;
194 }
195 if (!strcmp(item_name, namestr)) {
196 ret = PySequence_GetItem(obj->values, i);
197 goto bail;
198 }
199 }
200
201 PyErr_Format(
202 PyExc_AttributeError, "bserobject has no attribute '%.400s'", namestr);
203 bail:
204 Py_XDECREF(name_bytes);
205 return ret;
206 }
207
208 // clang-format off
209 static PyMappingMethods bserobj_map = {
210 bserobj_tuple_length, /* mp_length */
211 bserobj_getattrro, /* mp_subscript */
212 0 /* mp_ass_subscript */
213 };
214
215 PyTypeObject bserObjectType = {
216 PyVarObject_HEAD_INIT(NULL, 0)
217 "bserobj_tuple", /* tp_name */
218 sizeof(bserObject), /* tp_basicsize */
219 0, /* tp_itemsize */
220 bserobj_dealloc, /* tp_dealloc */
221 0, /* tp_print */
222 0, /* tp_getattr */
223 0, /* tp_setattr */
224 0, /* tp_compare */
225 0, /* tp_repr */
226 0, /* tp_as_number */
227 &bserobj_sq, /* tp_as_sequence */
228 &bserobj_map, /* tp_as_mapping */
229 0, /* tp_hash */
230 0, /* tp_call */
231 0, /* tp_str */
232 bserobj_getattrro, /* tp_getattro */
233 0, /* tp_setattro */
234 0, /* tp_as_buffer */
235 Py_TPFLAGS_DEFAULT, /* tp_flags */
236 "bserobj tuple", /* tp_doc */
237 0, /* tp_traverse */
238 0, /* tp_clear */
239 0, /* tp_richcompare */
240 0, /* tp_weaklistoffset */
241 0, /* tp_iter */
242 0, /* tp_iternext */
243 0, /* tp_methods */
244 0, /* tp_members */
245 0, /* tp_getset */
246 0, /* tp_base */
247 0, /* tp_dict */
248 0, /* tp_descr_get */
249 0, /* tp_descr_set */
250 0, /* tp_dictoffset */
251 0, /* tp_init */
252 0, /* tp_alloc */
253 0, /* tp_new */
254 };
255 // clang-format on
256
257 typedef struct loads_ctx {
258 int mutable;
259 const char* value_encoding;
260 const char* value_errors;
261 uint32_t bser_version;
262 uint32_t bser_capabilities;
263 } unser_ctx_t;
264
265 static PyObject*
266 bser_loads_recursive(const char** ptr, const char* end, const unser_ctx_t* ctx);
267
268 static const char bser_true = BSER_TRUE;
269 static const char bser_false = BSER_FALSE;
270 static const char bser_null = BSER_NULL;
271 static const char bser_bytestring_hdr = BSER_BYTESTRING;
272 static const char bser_array_hdr = BSER_ARRAY;
273 static const char bser_object_hdr = BSER_OBJECT;
274
275 static inline uint32_t next_power_2(uint32_t n) {
276 n |= (n >> 16);
277 n |= (n >> 8);
278 n |= (n >> 4);
279 n |= (n >> 2);
280 n |= (n >> 1);
281 return n + 1;
282 }
283
284 // A buffer we use for building up the serialized result
285 struct bser_buffer {
286 char* buf;
287 int wpos, allocd;
288 uint32_t bser_version;
289 uint32_t capabilities;
290 };
291 typedef struct bser_buffer bser_t;
292
293 static int bser_append(bser_t* bser, const char* data, uint32_t len) {
294 int newlen = next_power_2(bser->wpos + len);
295 if (newlen > bser->allocd) {
296 char* nbuf = realloc(bser->buf, newlen);
297 if (!nbuf) {
298 return 0;
299 }
300
301 bser->buf = nbuf;
302 bser->allocd = newlen;
303 }
304
305 memcpy(bser->buf + bser->wpos, data, len);
306 bser->wpos += len;
307 return 1;
308 }
309
310 static int bser_init(bser_t* bser, uint32_t version, uint32_t capabilities) {
311 bser->allocd = 8192;
312 bser->wpos = 0;
313 bser->buf = malloc(bser->allocd);
314 bser->bser_version = version;
315 bser->capabilities = capabilities;
316 if (!bser->buf) {
317 return 0;
318 }
319
320 // Leave room for the serialization header, which includes
321 // our overall length. To make things simpler, we'll use an
322 // int32 for the header
323 #define EMPTY_HEADER "\x00\x01\x05\x00\x00\x00\x00"
324
325 // Version 2 also carries an integer indicating the capabilities. The
326 // capabilities integer comes before the PDU size.
327 #define EMPTY_HEADER_V2 "\x00\x02\x00\x00\x00\x00\x05\x00\x00\x00\x00"
328 if (version == 2) {
329 bser_append(bser, EMPTY_HEADER_V2, sizeof(EMPTY_HEADER_V2) - 1);
330 } else {
331 bser_append(bser, EMPTY_HEADER, sizeof(EMPTY_HEADER) - 1);
332 }
333
334 return 1;
335 }
336
337 static void bser_dtor(bser_t* bser) {
338 free(bser->buf);
339 bser->buf = NULL;
340 }
341
342 static int bser_long(bser_t* bser, int64_t val) {
343 int8_t i8;
344 int16_t i16;
345 int32_t i32;
346 int64_t i64;
347 char sz;
348 int size = INT_SIZE(val);
349 char* iptr;
350
351 switch (size) {
352 case 1:
353 sz = BSER_INT8;
354 i8 = (int8_t)val;
355 iptr = (char*)&i8;
356 break;
357 case 2:
358 sz = BSER_INT16;
359 i16 = (int16_t)val;
360 iptr = (char*)&i16;
361 break;
362 case 4:
363 sz = BSER_INT32;
364 i32 = (int32_t)val;
365 iptr = (char*)&i32;
366 break;
367 case 8:
368 sz = BSER_INT64;
369 i64 = (int64_t)val;
370 iptr = (char*)&i64;
371 break;
372 default:
373 PyErr_SetString(PyExc_RuntimeError, "Cannot represent this long value!?");
374 return 0;
375 }
376
377 if (!bser_append(bser, &sz, sizeof(sz))) {
378 return 0;
379 }
380
381 return bser_append(bser, iptr, size);
382 }
383
384 static int bser_bytestring(bser_t* bser, PyObject* sval) {
385 char* buf = NULL;
386 Py_ssize_t len;
387 int res;
388 PyObject* utf = NULL;
389
390 if (PyUnicode_Check(sval)) {
391 utf = PyUnicode_AsEncodedString(sval, "utf-8", "ignore");
392 sval = utf;
393 }
394
395 res = PyBytes_AsStringAndSize(sval, &buf, &len);
396 if (res == -1) {
397 res = 0;
398 goto out;
399 }
400
401 if (!bser_append(bser, &bser_bytestring_hdr, sizeof(bser_bytestring_hdr))) {
402 res = 0;
403 goto out;
404 }
405
406 if (!bser_long(bser, len)) {
407 res = 0;
408 goto out;
409 }
410
411 if (len > UINT32_MAX) {
412 PyErr_Format(PyExc_ValueError, "string too big");
413 res = 0;
414 goto out;
415 }
416
417 res = bser_append(bser, buf, (uint32_t)len);
418
419 out:
420 if (utf) {
421 Py_DECREF(utf);
422 }
423
424 return res;
425 }
426
427 static int bser_recursive(bser_t* bser, PyObject* val) {
428 if (PyBool_Check(val)) {
429 if (val == Py_True) {
430 return bser_append(bser, &bser_true, sizeof(bser_true));
431 }
432 return bser_append(bser, &bser_false, sizeof(bser_false));
433 }
434
435 if (val == Py_None) {
436 return bser_append(bser, &bser_null, sizeof(bser_null));
437 }
438
439 // Python 3 has one integer type.
440 #if PY_MAJOR_VERSION < 3
441 if (PyInt_Check(val)) {
442 return bser_long(bser, PyInt_AS_LONG(val));
443 }
444 #endif // PY_MAJOR_VERSION < 3
445
446 if (PyLong_Check(val)) {
447 return bser_long(bser, PyLong_AsLongLong(val));
448 }
449
450 if (PyBytes_Check(val) || PyUnicode_Check(val)) {
451 return bser_bytestring(bser, val);
452 }
453
454 if (PyFloat_Check(val)) {
455 double dval = PyFloat_AS_DOUBLE(val);
456 char sz = BSER_REAL;
457
458 if (!bser_append(bser, &sz, sizeof(sz))) {
459 return 0;
460 }
461
462 return bser_append(bser, (char*)&dval, sizeof(dval));
463 }
464
465 if (PyList_Check(val)) {
466 Py_ssize_t i, len = PyList_GET_SIZE(val);
467
468 if (!bser_append(bser, &bser_array_hdr, sizeof(bser_array_hdr))) {
469 return 0;
470 }
471
472 if (!bser_long(bser, len)) {
473 return 0;
474 }
475
476 for (i = 0; i < len; i++) {
477 PyObject* ele = PyList_GET_ITEM(val, i);
478
479 if (!bser_recursive(bser, ele)) {
480 return 0;
481 }
482 }
483
484 return 1;
485 }
486
487 if (PyTuple_Check(val)) {
488 Py_ssize_t i, len = PyTuple_GET_SIZE(val);
489
490 if (!bser_append(bser, &bser_array_hdr, sizeof(bser_array_hdr))) {
491 return 0;
492 }
493
494 if (!bser_long(bser, len)) {
495 return 0;
496 }
497
498 for (i = 0; i < len; i++) {
499 PyObject* ele = PyTuple_GET_ITEM(val, i);
500
501 if (!bser_recursive(bser, ele)) {
502 return 0;
503 }
504 }
505
506 return 1;
507 }
508
509 if (PyMapping_Check(val)) {
510 Py_ssize_t len = PyMapping_Length(val);
511 Py_ssize_t pos = 0;
512 PyObject *key, *ele;
513
514 if (!bser_append(bser, &bser_object_hdr, sizeof(bser_object_hdr))) {
515 return 0;
516 }
517
518 if (!bser_long(bser, len)) {
519 return 0;
520 }
521
522 while (PyDict_Next(val, &pos, &key, &ele)) {
523 if (!bser_bytestring(bser, key)) {
524 return 0;
525 }
526 if (!bser_recursive(bser, ele)) {
527 return 0;
528 }
529 }
530
531 return 1;
532 }
533
534 PyErr_SetString(PyExc_ValueError, "Unsupported value type");
535 return 0;
536 }
537
538 static PyObject* bser_dumps(PyObject* self, PyObject* args, PyObject* kw) {
539 PyObject *val = NULL, *res;
540 bser_t bser;
541 uint32_t len, bser_version = 1, bser_capabilities = 0;
542
543 static char* kw_list[] = {"val", "version", "capabilities", NULL};
544
545 if (!PyArg_ParseTupleAndKeywords(
546 args,
547 kw,
548 "O|ii:dumps",
549 kw_list,
550 &val,
551 &bser_version,
552 &bser_capabilities)) {
553 return NULL;
554 }
555
556 if (!bser_init(&bser, bser_version, bser_capabilities)) {
557 return PyErr_NoMemory();
558 }
559
560 if (!bser_recursive(&bser, val)) {
561 bser_dtor(&bser);
562 if (errno == ENOMEM) {
563 return PyErr_NoMemory();
564 }
565 // otherwise, we've already set the error to something reasonable
566 return NULL;
567 }
568
569 // Now fill in the overall length
570 if (bser_version == 1) {
571 len = bser.wpos - (sizeof(EMPTY_HEADER) - 1);
572 memcpy(bser.buf + 3, &len, sizeof(len));
573 } else {
574 len = bser.wpos - (sizeof(EMPTY_HEADER_V2) - 1);
575 // The BSER capabilities block comes before the PDU length
576 memcpy(bser.buf + 2, &bser_capabilities, sizeof(bser_capabilities));
577 memcpy(bser.buf + 7, &len, sizeof(len));
578 }
579
580 res = PyBytes_FromStringAndSize(bser.buf, bser.wpos);
581 bser_dtor(&bser);
582
583 return res;
584 }
585
586 int bunser_int(const char** ptr, const char* end, int64_t* val) {
587 int needed;
588 const char* buf = *ptr;
589 int8_t i8;
590 int16_t i16;
591 int32_t i32;
592 int64_t i64;
593
594 switch (buf[0]) {
595 case BSER_INT8:
596 needed = 2;
597 break;
598 case BSER_INT16:
599 needed = 3;
600 break;
601 case BSER_INT32:
602 needed = 5;
603 break;
604 case BSER_INT64:
605 needed = 9;
606 break;
607 default:
608 PyErr_Format(
609 PyExc_ValueError, "invalid bser int encoding 0x%02x", buf[0]);
610 return 0;
611 }
612 if (end - buf < needed) {
613 PyErr_SetString(PyExc_ValueError, "input buffer to small for int encoding");
614 return 0;
615 }
616 *ptr = buf + needed;
617 switch (buf[0]) {
618 case BSER_INT8:
619 memcpy(&i8, buf + 1, sizeof(i8));
620 *val = i8;
621 return 1;
622 case BSER_INT16:
623 memcpy(&i16, buf + 1, sizeof(i16));
624 *val = i16;
625 return 1;
626 case BSER_INT32:
627 memcpy(&i32, buf + 1, sizeof(i32));
628 *val = i32;
629 return 1;
630 case BSER_INT64:
631 memcpy(&i64, buf + 1, sizeof(i64));
632 *val = i64;
633 return 1;
634 default:
635 return 0;
636 }
637 }
638
639 static int bunser_bytestring(
640 const char** ptr,
641 const char* end,
642 const char** start,
643 int64_t* len) {
644 const char* buf = *ptr;
645
646 // skip string marker
647 buf++;
648 if (!bunser_int(&buf, end, len)) {
649 return 0;
650 }
651
652 if (buf + *len > end) {
653 PyErr_Format(PyExc_ValueError, "invalid string length in bser data");
654 return 0;
655 }
656
657 *ptr = buf + *len;
658 *start = buf;
659 return 1;
660 }
661
662 static PyObject*
663 bunser_array(const char** ptr, const char* end, const unser_ctx_t* ctx) {
664 const char* buf = *ptr;
665 int64_t nitems, i;
666 int mutable = ctx->mutable;
667 PyObject* res;
668
669 // skip array header
670 buf++;
671 if (!bunser_int(&buf, end, &nitems)) {
672 return 0;
673 }
674 *ptr = buf;
675
676 if (nitems > LONG_MAX) {
677 PyErr_Format(PyExc_ValueError, "too many items for python array");
678 return NULL;
679 }
680
681 if (mutable) {
682 res = PyList_New((Py_ssize_t)nitems);
683 } else {
684 res = PyTuple_New((Py_ssize_t)nitems);
685 }
686
687 for (i = 0; i < nitems; i++) {
688 PyObject* ele = bser_loads_recursive(ptr, end, ctx);
689
690 if (!ele) {
691 Py_DECREF(res);
692 return NULL;
693 }
694
695 if (mutable) {
696 PyList_SET_ITEM(res, i, ele);
697 } else {
698 PyTuple_SET_ITEM(res, i, ele);
699 }
700 // DECREF(ele) not required as SET_ITEM steals the ref
701 }
702
703 return res;
704 }
705
706 static PyObject*
707 bunser_object(const char** ptr, const char* end, const unser_ctx_t* ctx) {
708 const char* buf = *ptr;
709 int64_t nitems, i;
710 int mutable = ctx->mutable;
711 PyObject* res;
712 bserObject* obj;
713
714 // skip array header
715 buf++;
716 if (!bunser_int(&buf, end, &nitems)) {
717 return 0;
718 }
719 *ptr = buf;
720
721 if (mutable) {
722 res = PyDict_New();
723 } else {
724 obj = PyObject_New(bserObject, &bserObjectType);
725 obj->keys = PyTuple_New((Py_ssize_t)nitems);
726 obj->values = PyTuple_New((Py_ssize_t)nitems);
727 res = (PyObject*)obj;
728 }
729
730 for (i = 0; i < nitems; i++) {
731 const char* keystr;
732 int64_t keylen;
733 PyObject* key;
734 PyObject* ele;
735
736 if (!bunser_bytestring(ptr, end, &keystr, &keylen)) {
737 Py_DECREF(res);
738 return NULL;
739 }
740
741 if (keylen > LONG_MAX) {
742 PyErr_Format(PyExc_ValueError, "string too big for python");
743 Py_DECREF(res);
744 return NULL;
745 }
746
747 if (mutable) {
748 // This will interpret the key as UTF-8.
749 key = PyUnicode_FromStringAndSize(keystr, (Py_ssize_t)keylen);
750 } else {
751 // For immutable objects we'll manage key lookups, so we can avoid going
752 // through the Unicode APIs. This avoids a potentially expensive and
753 // definitely unnecessary conversion to UTF-16 and back for Python 2.
754 // TODO: On Python 3 the Unicode APIs are smarter: we might be able to use
755 // Unicode keys there without an appreciable performance loss.
756 key = PyBytes_FromStringAndSize(keystr, (Py_ssize_t)keylen);
757 }
758
759 if (!key) {
760 Py_DECREF(res);
761 return NULL;
762 }
763
764 ele = bser_loads_recursive(ptr, end, ctx);
765
766 if (!ele) {
767 Py_DECREF(key);
768 Py_DECREF(res);
769 return NULL;
770 }
771
772 if (mutable) {
773 PyDict_SetItem(res, key, ele);
774 Py_DECREF(key);
775 Py_DECREF(ele);
776 } else {
777 /* PyTuple_SET_ITEM steals ele, key */
778 PyTuple_SET_ITEM(obj->values, i, ele);
779 PyTuple_SET_ITEM(obj->keys, i, key);
780 }
781 }
782
783 return res;
784 }
785
786 static PyObject*
787 bunser_template(const char** ptr, const char* end, const unser_ctx_t* ctx) {
788 const char* buf = *ptr;
789 int64_t nitems, i;
790 int mutable = ctx->mutable;
791 PyObject* arrval;
792 PyObject* keys;
793 Py_ssize_t numkeys, keyidx;
794 unser_ctx_t keys_ctx = {0};
795 if (mutable) {
796 keys_ctx.mutable = 1;
797 // Decode keys as UTF-8 in this case.
798 keys_ctx.value_encoding = "utf-8";
799 keys_ctx.value_errors = "strict";
800 } else {
801 // Treat keys as bytestrings in this case -- we'll do Unicode conversions at
802 // lookup time.
803 }
804
805 if (buf[1] != BSER_ARRAY) {
806 PyErr_Format(PyExc_ValueError, "Expect ARRAY to follow TEMPLATE");
807 return NULL;
808 }
809
810 // skip header
811 buf++;
812 *ptr = buf;
813
814 // Load template keys.
815 // For keys we don't want to do any decoding right now.
816 keys = bunser_array(ptr, end, &keys_ctx);
817 if (!keys) {
818 return NULL;
819 }
820
821 numkeys = PySequence_Length(keys);
822
823 // Load number of array elements
824 if (!bunser_int(ptr, end, &nitems)) {
825 Py_DECREF(keys);
826 return 0;
827 }
828
829 if (nitems > LONG_MAX) {
830 PyErr_Format(PyExc_ValueError, "Too many items for python");
831 Py_DECREF(keys);
832 return NULL;
833 }
834
835 arrval = PyList_New((Py_ssize_t)nitems);
836 if (!arrval) {
837 Py_DECREF(keys);
838 return NULL;
839 }
840
841 for (i = 0; i < nitems; i++) {
842 PyObject* dict = NULL;
843 bserObject* obj = NULL;
844
845 if (mutable) {
846 dict = PyDict_New();
847 } else {
848 obj = PyObject_New(bserObject, &bserObjectType);
849 if (obj) {
850 obj->keys = keys;
851 Py_INCREF(obj->keys);
852 obj->values = PyTuple_New(numkeys);
853 }
854 dict = (PyObject*)obj;
855 }
856 if (!dict) {
857 fail:
858 Py_DECREF(keys);
859 Py_DECREF(arrval);
860 return NULL;
861 }
862
863 for (keyidx = 0; keyidx < numkeys; keyidx++) {
864 PyObject* key;
865 PyObject* ele;
866
867 if (**ptr == BSER_SKIP) {
868 *ptr = *ptr + 1;
869 ele = Py_None;
870 Py_INCREF(ele);
871 } else {
872 ele = bser_loads_recursive(ptr, end, ctx);
873 }
874
875 if (!ele) {
876 goto fail;
877 }
878
879 if (mutable) {
880 key = PyList_GET_ITEM(keys, keyidx);
881 PyDict_SetItem(dict, key, ele);
882 Py_DECREF(ele);
883 } else {
884 PyTuple_SET_ITEM(obj->values, keyidx, ele);
885 // DECREF(ele) not required as SET_ITEM steals the ref
886 }
887 }
888
889 PyList_SET_ITEM(arrval, i, dict);
890 // DECREF(obj) not required as SET_ITEM steals the ref
891 }
892
893 Py_DECREF(keys);
894
895 return arrval;
896 }
897
898 static PyObject* bser_loads_recursive(
899 const char** ptr,
900 const char* end,
901 const unser_ctx_t* ctx) {
902 const char* buf = *ptr;
903
904 switch (buf[0]) {
905 case BSER_INT8:
906 case BSER_INT16:
907 case BSER_INT32:
908 case BSER_INT64: {
909 int64_t ival;
910 if (!bunser_int(ptr, end, &ival)) {
911 return NULL;
912 }
913 // Python 3 has one integer type.
914 #if PY_MAJOR_VERSION >= 3
915 return PyLong_FromLongLong(ival);
916 #else
917 if (ival < LONG_MIN || ival > LONG_MAX) {
918 return PyLong_FromLongLong(ival);
919 }
920 return PyInt_FromSsize_t(Py_SAFE_DOWNCAST(ival, int64_t, Py_ssize_t));
921 #endif // PY_MAJOR_VERSION >= 3
922 }
923
924 case BSER_REAL: {
925 double dval;
926 memcpy(&dval, buf + 1, sizeof(dval));
927 *ptr = buf + 1 + sizeof(double);
928 return PyFloat_FromDouble(dval);
929 }
930
931 case BSER_TRUE:
932 *ptr = buf + 1;
933 Py_INCREF(Py_True);
934 return Py_True;
935
936 case BSER_FALSE:
937 *ptr = buf + 1;
938 Py_INCREF(Py_False);
939 return Py_False;
940
941 case BSER_NULL:
942 *ptr = buf + 1;
943 Py_INCREF(Py_None);
944 return Py_None;
945
946 case BSER_BYTESTRING: {
947 const char* start;
948 int64_t len;
949
950 if (!bunser_bytestring(ptr, end, &start, &len)) {
951 return NULL;
952 }
953
954 if (len > LONG_MAX) {
955 PyErr_Format(PyExc_ValueError, "string too long for python");
956 return NULL;
957 }
958
959 if (ctx->value_encoding != NULL) {
960 return PyUnicode_Decode(
961 start, (long)len, ctx->value_encoding, ctx->value_errors);
962 } else {
963 return PyBytes_FromStringAndSize(start, (long)len);
964 }
965 }
966
967 case BSER_UTF8STRING: {
968 const char* start;
969 int64_t len;
970
971 if (!bunser_bytestring(ptr, end, &start, &len)) {
972 return NULL;
973 }
974
975 if (len > LONG_MAX) {
976 PyErr_Format(PyExc_ValueError, "string too long for python");
977 return NULL;
978 }
979
980 return PyUnicode_Decode(start, (long)len, "utf-8", "strict");
981 }
982
983 case BSER_ARRAY:
984 return bunser_array(ptr, end, ctx);
985
986 case BSER_OBJECT:
987 return bunser_object(ptr, end, ctx);
988
989 case BSER_TEMPLATE:
990 return bunser_template(ptr, end, ctx);
991
992 default:
993 PyErr_Format(PyExc_ValueError, "unhandled bser opcode 0x%02x", buf[0]);
994 }
995
996 return NULL;
997 }
998
999 static int _pdu_info_helper(
1000 const char* data,
1001 const char* end,
1002 uint32_t* bser_version_out,
1003 uint32_t* bser_capabilities_out,
1004 int64_t* expected_len_out,
1005 off_t* position_out) {
1006 uint32_t bser_version;
1007 uint32_t bser_capabilities = 0;
1008 int64_t expected_len;
1009
1010 const char* start;
1011 start = data;
1012 // Validate the header and length
1013 if (memcmp(data, EMPTY_HEADER, 2) == 0) {
1014 bser_version = 1;
1015 } else if (memcmp(data, EMPTY_HEADER_V2, 2) == 0) {
1016 bser_version = 2;
1017 } else {
1018 PyErr_SetString(PyExc_ValueError, "invalid bser header");
1019 return 0;
1020 }
1021
1022 data += 2;
1023
1024 if (bser_version == 2) {
1025 // Expect an integer telling us what capabilities are supported by the
1026 // remote server (currently unused).
1027 if (!memcpy(&bser_capabilities, &data, sizeof(bser_capabilities))) {
1028 return 0;
1029 }
1030 data += sizeof(bser_capabilities);
1031 }
1032
1033 // Expect an integer telling us how big the rest of the data
1034 // should be
1035 if (!bunser_int(&data, end, &expected_len)) {
1036 return 0;
1037 }
1038
1039 *bser_version_out = bser_version;
1040 *bser_capabilities_out = (uint32_t)bser_capabilities;
1041 *expected_len_out = expected_len;
1042 *position_out = (off_t)(data - start);
1043 return 1;
1044 }
1045
1046 // This function parses the PDU header and provides info about the packet
1047 // Returns false if unsuccessful
1048 static int pdu_info_helper(
1049 PyObject* self,
1050 PyObject* args,
1051 uint32_t* bser_version_out,
1052 uint32_t* bser_capabilities_out,
1053 int64_t* total_len_out) {
1054 const char* start = NULL;
1055 const char* data = NULL;
1056 Py_ssize_t datalen = 0;
1057 const char* end;
1058 int64_t expected_len;
1059 off_t position;
1060
1061 if (!PyArg_ParseTuple(args, "s#", &start, &datalen)) {
1062 return 0;
1063 }
1064 data = start;
1065 end = data + datalen;
1066
1067 if (!_pdu_info_helper(
1068 data,
1069 end,
1070 bser_version_out,
1071 bser_capabilities_out,
1072 &expected_len,
1073 &position)) {
1074 return 0;
1075 }
1076 *total_len_out = (int64_t)(expected_len + position);
1077 return 1;
1078 }
1079
1080 // Expected use case is to read a packet from the socket and then call
1081 // bser.pdu_info on the packet. It returns the BSER version, BSER capabilities,
1082 // and the total length of the entire response that the peer is sending,
1083 // including the bytes already received. This allows the client to compute the
1084 // data size it needs to read before it can decode the data.
1085 static PyObject* bser_pdu_info(PyObject* self, PyObject* args) {
1086 uint32_t version, capabilities;
1087 int64_t total_len;
1088 if (!pdu_info_helper(self, args, &version, &capabilities, &total_len)) {
1089 return NULL;
1090 }
1091 return Py_BuildValue("kkL", version, capabilities, total_len);
1092 }
1093
1094 static PyObject* bser_pdu_len(PyObject* self, PyObject* args) {
1095 uint32_t version, capabilities;
1096 int64_t total_len;
1097 if (!pdu_info_helper(self, args, &version, &capabilities, &total_len)) {
1098 return NULL;
1099 }
1100 return Py_BuildValue("L", total_len);
1101 }
1102
1103 static PyObject* bser_loads(PyObject* self, PyObject* args, PyObject* kw) {
1104 const char* data = NULL;
1105 Py_ssize_t datalen = 0;
1106 const char* start;
1107 const char* end;
1108 int64_t expected_len;
1109 off_t position;
1110 PyObject* mutable_obj = NULL;
1111 const char* value_encoding = NULL;
1112 const char* value_errors = NULL;
1113 unser_ctx_t ctx = {1, 0};
1114
1115 static char* kw_list[] = {
1116 "buf", "mutable", "value_encoding", "value_errors", NULL};
1117
1118 if (!PyArg_ParseTupleAndKeywords(
1119 args,
1120 kw,
1121 "s#|Ozz:loads",
1122 kw_list,
1123 &start,
1124 &datalen,
1125 &mutable_obj,
1126 &value_encoding,
1127 &value_errors)) {
1128 return NULL;
1129 }
1130
1131 if (mutable_obj) {
1132 ctx.mutable = PyObject_IsTrue(mutable_obj) > 0 ? 1 : 0;
1133 }
1134 ctx.value_encoding = value_encoding;
1135 if (value_encoding == NULL) {
1136 ctx.value_errors = NULL;
1137 } else if (value_errors == NULL) {
1138 ctx.value_errors = "strict";
1139 } else {
1140 ctx.value_errors = value_errors;
1141 }
1142 data = start;
1143 end = data + datalen;
1144
1145 if (!_pdu_info_helper(
1146 data,
1147 end,
1148 &ctx.bser_version,
1149 &ctx.bser_capabilities,
1150 &expected_len,
1151 &position)) {
1152 return NULL;
1153 }
1154
1155 data = start + position;
1156 // Verify
1157 if (expected_len + data != end) {
1158 PyErr_SetString(PyExc_ValueError, "bser data len != header len");
1159 return NULL;
1160 }
1161
1162 return bser_loads_recursive(&data, end, &ctx);
1163 }
1164
1165 static PyObject* bser_load(PyObject* self, PyObject* args, PyObject* kw) {
1166 PyObject* load;
1167 PyObject* load_method;
1168 PyObject* string;
1169 PyObject* load_method_args;
1170 PyObject* load_method_kwargs;
1171 PyObject* fp = NULL;
1172 PyObject* mutable_obj = NULL;
1173 PyObject* value_encoding = NULL;
1174 PyObject* value_errors = NULL;
1175
1176 static char* kw_list[] = {
1177 "fp", "mutable", "value_encoding", "value_errors", NULL};
1178
1179 if (!PyArg_ParseTupleAndKeywords(
1180 args,
1181 kw,
1182 "O|OOO:load",
1183 kw_list,
1184 &fp,
1185 &mutable_obj,
1186 &value_encoding,
1187 &value_errors)) {
1188 return NULL;
1189 }
1190
1191 load = PyImport_ImportModule("pywatchman.load");
1192 if (load == NULL) {
1193 return NULL;
1194 }
1195 load_method = PyObject_GetAttrString(load, "load");
1196 if (load_method == NULL) {
1197 return NULL;
1198 }
1199 // Mandatory method arguments
1200 load_method_args = Py_BuildValue("(O)", fp);
1201 if (load_method_args == NULL) {
1202 return NULL;
1203 }
1204 // Optional method arguments
1205 load_method_kwargs = PyDict_New();
1206 if (load_method_kwargs == NULL) {
1207 return NULL;
1208 }
1209 if (mutable_obj) {
1210 PyDict_SetItemString(load_method_kwargs, "mutable", mutable_obj);
1211 }
1212 if (value_encoding) {
1213 PyDict_SetItemString(load_method_kwargs, "value_encoding", value_encoding);
1214 }
1215 if (value_errors) {
1216 PyDict_SetItemString(load_method_kwargs, "value_errors", value_errors);
1217 }
1218 string = PyObject_Call(load_method, load_method_args, load_method_kwargs);
1219 Py_DECREF(load_method_kwargs);
1220 Py_DECREF(load_method_args);
1221 Py_DECREF(load_method);
1222 Py_DECREF(load);
1223 return string;
1224 }
1225
1226 // clang-format off
1227 static PyMethodDef bser_methods[] = {
1228 {"loads", (PyCFunction)bser_loads, METH_VARARGS | METH_KEYWORDS,
1229 "Deserialize string."},
1230 {"load", (PyCFunction)bser_load, METH_VARARGS | METH_KEYWORDS,
1231 "Deserialize a file object"},
1232 {"pdu_info", (PyCFunction)bser_pdu_info, METH_VARARGS,
1233 "Extract PDU information."},
1234 {"pdu_len", (PyCFunction)bser_pdu_len, METH_VARARGS,
1235 "Extract total PDU length."},
1236 {"dumps", (PyCFunction)bser_dumps, METH_VARARGS | METH_KEYWORDS,
1237 "Serialize string."},
1238 {NULL, NULL, 0, NULL}
1239 };
1240
1241 #if PY_MAJOR_VERSION >= 3
1242 static struct PyModuleDef bser_module = {
1243 PyModuleDef_HEAD_INIT,
1244 "bser",
1245 "Efficient encoding and decoding of BSER.",
1246 -1,
1247 bser_methods
1248 };
1249 // clang-format on
1250
1251 PyMODINIT_FUNC PyInit_bser(void) {
1252 PyObject* mod;
1253
1254 mod = PyModule_Create(&bser_module);
1255 PyType_Ready(&bserObjectType);
1256
1257 return mod;
1258 }
1259 #else
1260
1261 PyMODINIT_FUNC initbser(void) {
1262 (void)Py_InitModule("bser", bser_methods);
1263 PyType_Ready(&bserObjectType);
1264 }
1265 #endif // PY_MAJOR_VERSION >= 3
1266
1267 /* vim:ts=2:sw=2:et:
1268 */