-
Notifications
You must be signed in to change notification settings - Fork 106
/
cpython.c
3988 lines (3540 loc) · 102 KB
/
cpython.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2013-2024 The py-lmdb authors, all rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted only as authorized by the OpenLDAP
* Public License.
*
* A copy of this license is available in the file LICENSE in the
* top-level directory of the distribution or, alternatively, at
* <http://www.OpenLDAP.org/license.html>.
*
* OpenLDAP is a registered trademark of the OpenLDAP Foundation.
*
* Individual files and/or contributed packages may be copyright by
* other parties and/or subject to additional restrictions.
*
* This work also contains materials derived from public sources.
*
* Additional information about OpenLDAP can be obtained at
* <http://www.openldap.org/>.
*/
#define PY_SSIZE_T_CLEAN
/* Include order matters! */
#include "Python.h"
/* Search lib/win32 first, then fallthrough to <stdint.h> as required.*/
#include "stdint.h"
#include <errno.h>
#include <stdarg.h>
#include <string.h>
#ifdef _WIN32
# define bool int
# define true 1
# define false 0
#else
# include <stdbool.h>
#endif
#include <sys/stat.h>
#include "structmember.h"
#ifdef HAVE_MEMSINK
#define USING_MEMSINK
#include "memsink.h"
#endif
#ifdef _WIN32
#include <windows.h> /* HANDLE */
#endif
#include "lmdb.h"
#include "preload.h"
/* Comment out for copious debug. */
#define NODEBUG
#ifdef NODEBUG
# define DEBUG(s, ...)
#else
# define DEBUG(s, ...) fprintf(stderr, \
"lmdb.cpython: %s:%d: " s "\n", __func__, __LINE__, ## __VA_ARGS__);
#endif
#define MDEBUG(s, ...) DEBUG("%p: " s, self, ## __VA_ARGS__);
/* Inlining control for compatible compilers. */
#if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
# define NOINLINE __attribute__((noinline))
#else
# define NOINLINE
#endif
/**
* On Win32, Environment.copyfd() needs _get_osfmodule() from the C library,
* except that function performs no input validation. So instead we import
* msvcrt standard library module, which wraps _get_osfmodule() in a way that
* is crash-safe.
*/
#ifdef _WIN32
static PyObject *msvcrt;
#endif
/** PyLong representing integer 0. */
static PyObject *py_zero;
/** PyLong representing INT_MAX. */
static PyObject *py_int_max;
/** PyLong representing SIZE_MAX. */
static PyObject *py_size_max;
/** lmdb.Error type. */
static PyObject *Error;
/** Typedefs and forward declarations. */
static PyTypeObject PyDatabase_Type;
static PyTypeObject PyEnvironment_Type;
static PyTypeObject PyTransaction_Type;
static PyTypeObject PyCursor_Type;
static PyTypeObject PyIterator_Type;
typedef struct CursorObject CursorObject;
typedef struct DbObject DbObject;
typedef struct EnvObject EnvObject;
typedef struct IterObject IterObject;
typedef struct TransObject TransObject;
# define MOD_RETURN(mod) return mod;
# define MODINIT_NAME PyInit_cpython
# define MAKE_ID(id) PyCapsule_New((void *) (1 + (id)), NULL, NULL)
# define READ_ID(obj) (((int) (long) PyCapsule_GetPointer(obj, NULL)) - 1)
struct list_head {
struct lmdb_object *prev;
struct lmdb_object *next;
};
#define LmdbObject_HEAD \
PyObject_HEAD \
struct list_head siblings; \
struct list_head children; \
int valid;
struct lmdb_object {
LmdbObject_HEAD
};
#define OBJECT_INIT(o) \
((struct lmdb_object *)o)->siblings.prev = NULL; \
((struct lmdb_object *)o)->siblings.next = NULL; \
((struct lmdb_object *)o)->children.prev = NULL; \
((struct lmdb_object *)o)->children.next = NULL; \
((struct lmdb_object *)o)->valid = 1;
/** lmdb._Database */
struct DbObject {
LmdbObject_HEAD
/** Python Environment reference. Not refcounted; when the last strong ref
* to Environment is released, DbObject.tp_clear() will be called, causing
* DbObject.env and DbObject.dbi to be cleared. This is to prevent a
* cyclical reference from DB->Env keeping the environment alive. */
struct EnvObject *env;
/** MDB database handle. */
MDB_dbi dbi;
/** Flags at time of creation. */
unsigned int flags;
};
/** lmdb.Environment */
struct EnvObject {
LmdbObject_HEAD
/** Python-managed list of weakrefs to this object. */
PyObject *weaklist;
/** MDB environment object. */
MDB_env *env;
/** DBI for main database, opened during Environment construction. */
DbObject *main_db;
/** 1 if env opened read-only; transactions must always be read-only. */
int readonly;
/** Spare read-only transaction . */
struct MDB_txn *spare_txn;
};
/** TransObject.flags bitfield values. */
enum trans_flags {
/** Buffers should be yielded by get. */
TRANS_BUFFERS = 1,
/** Transaction can be can go on freelist instead of deallocation. */
TRANS_RDONLY = 2,
/** Transaction is spare, ready for mdb_txn_renew() */
TRANS_SPARE = 4
};
/** lmdb.Transaction */
struct TransObject {
LmdbObject_HEAD
/** Python-managed list of weakrefs to this object. */
PyObject *weaklist;
EnvObject *env;
#ifdef HAVE_MEMSINK
/** Copy-on-invalid list head. */
PyObject *sink_head;
#endif
/** MDB transaction object. */
MDB_txn *txn;
/** Bitfield of trans_flags values. */
int flags;
/** Default database if none specified. */
DbObject *db;
/** Number of mutations occurred since start of transaction. Required to
* know when cursor key/value must be refreshed. */
int mutations;
};
/** lmdb.Cursor */
struct CursorObject {
LmdbObject_HEAD
/** Transaction cursor belongs to. */
TransObject *trans;
/** 1 if mdb_cursor_get() has been called and it last returned 0. */
int positioned;
/** MDB-level cursor object. */
MDB_cursor *curs;
/** mv_size==0 if positioned==0, otherwise points to current key. */
MDB_val key;
/** mv_size==0 if positioned==0, otherwise points to current value. */
MDB_val val;
/** If TransObject.mutations!=last_mutation, must MDB_GET_CURRENT to
* refresh `key' and `val'. */
int last_mutation;
/** DBI flags at time of creation. */
unsigned int dbi_flags;
};
typedef PyObject *(*IterValFunc)(CursorObject *);
/** lmdb.Iterator
*
* This is separate from Cursor since we want to define Cursor.next() to mean
* MDB_NEXT, and a Python iterator's next() has different semantics.
*/
struct IterObject {
PyObject_HEAD
/** Cursor being iterated, or NULL for freelist iterator. */
CursorObject *curs;
/** 1 if iteration has started (Cursor should advance on next()). */
int started;
/** Operation used to advance cursor. */
MDB_cursor_op op;
/** Iterator value function, should be item(), key(), or value(). */
IterValFunc val_func;
};
/**
* Link `child` into `parent`'s list of dependent objects. Use LINK_CHILD()
* maro to avoid casting PyObject to lmdb_object.
*/
static void link_child(struct lmdb_object *parent, struct lmdb_object *child)
{
struct lmdb_object *sibling = parent->children.next;
if(sibling) {
child->siblings.next = sibling;
sibling->siblings.prev = child;
}
parent->children.next = child;
}
#define LINK_CHILD(parent, child) link_child((void *)parent, (void *)child);
/**
* Remove `child` from `parent`'s list of dependent objects. Use UNLINK_CHILD
* macro to avoid casting PyObject to lmdb_object.
*/
static void unlink_child(struct lmdb_object *parent, struct lmdb_object *child)
{
if(parent) {
struct lmdb_object *prev = child->siblings.prev;
struct lmdb_object *next = child->siblings.next;
if(prev) {
prev->siblings.next = next;
/* If double unlink_child(), this test my legitimately fail: */
} else if(parent->children.next == child) {
parent->children.next = next;
}
if(next) {
next->siblings.prev = prev;
}
child->siblings.prev = NULL;
child->siblings.next = NULL;
}
}
#define UNLINK_CHILD(parent, child) unlink_child((void *)parent, (void *)child);
/**
* Notify dependents of `parent` that `parent` is about to become invalid,
* and that they should free any dependent resources.
*
* To save effort, tp_clear is overloaded to be the invalidation function,
* instead of carrying a separate pointer. Objects are added to their parent's
* list during construction and removed during deallocation.
*
* When the environment is closed, it walks its list calling tp_clear on each
* child, which in turn walk their own lists. Child transactions are added to
* their parent transaction's list. Iterators keep no significant state, so
* they are not tracked.
*
* Use INVALIDATE() macro to avoid casting PyObject to lmdb_object.
*/
static void invalidate(struct lmdb_object *parent)
{
struct lmdb_object *child = parent->children.next;
while(child) {
struct lmdb_object *next = child->siblings.next;
DEBUG("invalidating parent=%p child %p", parent, child)
Py_TYPE(child)->tp_clear((PyObject *) child);
child = next;
}
}
#define INVALIDATE(parent) invalidate((void *)parent);
/* ---------- */
/* Exceptions */
/* ---------- */
struct error_map {
int code;
const char *name;
};
/** Array of Error subclasses corresponding to `error_map'. */
static PyObject **error_tbl;
/** Mapping from LMDB error code to py-lmdb exception class. */
static const struct error_map error_map[] = {
{MDB_KEYEXIST, "KeyExistsError"},
{MDB_NOTFOUND, "NotFoundError"},
{MDB_PAGE_NOTFOUND, "PageNotFoundError"},
{MDB_CORRUPTED, "CorruptedError"},
{MDB_PANIC, "PanicError"},
{MDB_VERSION_MISMATCH, "VersionMismatchError"},
{MDB_INVALID, "InvalidError"},
{MDB_MAP_FULL, "MapFullError"},
{MDB_DBS_FULL, "DbsFullError"},
{MDB_READERS_FULL, "ReadersFullError"},
{MDB_TLS_FULL, "TlsFullError"},
{MDB_TXN_FULL, "TxnFullError"},
{MDB_CURSOR_FULL, "CursorFullError"},
{MDB_PAGE_FULL, "PageFullError"},
{MDB_MAP_RESIZED, "MapResizedError"},
{MDB_INCOMPATIBLE, "IncompatibleError"},
{MDB_BAD_RSLOT, "BadRslotError"},
{MDB_BAD_DBI, "BadDbiError"},
{MDB_BAD_TXN, "BadTxnError"},
{MDB_BAD_VALSIZE, "BadValsizeError"},
{EACCES, "ReadonlyError"},
{EINVAL, "InvalidParameterError"},
{EAGAIN, "LockError"},
{ENOMEM, "MemoryError"},
{ENOSPC, "DiskError"}
};
/* ---------- */
/* Exceptions */
/* ---------- */
/**
* Raise an exception appropriate for the given `rc` MDB error code.
*/
static void * NOINLINE
err_set(const char *what, int rc)
{
size_t count = sizeof error_map / sizeof error_map[0];
PyObject *klass = Error;
size_t i;
if(rc) {
for(i = 0; i < count; i++) {
if(error_map[i].code == rc) {
klass = error_tbl[i];
break;
}
}
}
PyErr_Format(klass, "%s: %s", what, mdb_strerror(rc));
return NULL;
}
/**
* Raise an exception from a format string.
*/
static void * NOINLINE
err_format(int rc, const char *fmt, ...)
{
char buf[128];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof buf, fmt, ap);
buf[sizeof buf - 1] = '\0';
va_end(ap);
return err_set(buf, rc);
}
static void * NOINLINE
err_invalid(void)
{
PyErr_Format(Error, "Attempt to operate on closed/deleted/dropped object.");
return NULL;
}
static void * NOINLINE
type_error(const char *what)
{
PyErr_Format(PyExc_TypeError, "%s", what);
return NULL;
}
/**
* Convert a PyObject to filesystem bytes. Must call fspath_fini() when done.
* Return 0 on success, or set an exception and return -1 on failure.
*/
static PyObject *
get_fspath(PyObject *src)
{
if(PyBytes_CheckExact(src)) {
Py_INCREF(src);
return src;
}
if(! PyUnicode_CheckExact(src)) {
type_error("Filesystem path must be Unicode or bytes.");
return NULL;
}
return PyUnicode_AsEncodedString(src, Py_FileSystemDefaultEncoding,
"strict");
}
/* ------- */
/* Helpers */
/* ------- */
/**
* Describes the type of a struct field.
*/
enum field_type {
/** Last field in set, stop converting. */
TYPE_EOF,
/** Unsigned 32bit integer. */
TYPE_UINT,
/** size_t */
TYPE_SIZE,
/** void pointer */
TYPE_ADDR
};
/**
* Describes a struct field.
*/
struct dict_field {
/** Field type. */
enum field_type type;
/** Field name in target dict. */
const char *name;
/* Offset into structure where field is found. */
int offset;
};
/**
* Return a new reference to Py_True if the given argument is true, otherwise
* a new reference to Py_False.
*/
static PyObject *
py_bool(int pred)
{
PyObject *obj = pred ? Py_True : Py_False;
Py_INCREF(obj);
return obj;
}
/**
* Convert the structure `o` described by `fields` to a dict and return the new
* dict.
*/
static PyObject *
dict_from_fields(void *o, const struct dict_field *fields)
{
PyObject *dict = PyDict_New();
if(! dict) {
return NULL;
}
while(fields->type != TYPE_EOF) {
uint8_t *p = ((uint8_t *) o) + fields->offset;
unsigned PY_LONG_LONG l = 0;
PyObject *lo;
if(fields->type == TYPE_UINT) {
l = *(unsigned int *)p;
} else if(fields->type == TYPE_SIZE) {
l = *(size_t *)p;
} else if(fields->type == TYPE_ADDR) {
l = (intptr_t) *(void **)p;
}
if(! ((lo = PyLong_FromUnsignedLongLong(l)))) {
Py_DECREF(dict);
return NULL;
}
if(PyDict_SetItemString(dict, fields->name, lo)) {
Py_DECREF(lo);
Py_DECREF(dict);
return NULL;
}
Py_DECREF(lo);
fields++;
}
return dict;
}
/**
* Given an MDB_val `val`, convert it to a Python string or bytes object,
* depending on the Python version. Returns a new reference to the object on
* sucess, or NULL on failure.
*/
static PyObject *
obj_from_val(MDB_val *val, int as_buffer)
{
if(as_buffer) {
return PyMemoryView_FromMemory(val->mv_data, val->mv_size, PyBUF_READ);
}
return PyBytes_FromStringAndSize(val->mv_data, val->mv_size);
}
/**
* Given some Python object, try to get at its raw data. For string or bytes
* objects, this is the object value. For Unicode objects, this is the UTF-8
* representation of the object value. For all other objects, attempt to invoke
* the Python 2.x buffer protocol.
*/
static int NOINLINE
val_from_buffer(MDB_val *val, PyObject *buf)
{
if(PyBytes_CheckExact(buf)) {
val->mv_data = PyBytes_AS_STRING(buf);
val->mv_size = PyBytes_GET_SIZE(buf);
return 0;
}
if(PyUnicode_CheckExact(buf)) {
type_error("Won't implicitly convert Unicode to bytes; use .encode()");
return -1;
}
return PyObject_AsReadBuffer(buf,
(const void **) &val->mv_data,
(Py_ssize_t *) &val->mv_size);
}
/* ------------------- */
/* Concurrency control */
/* ------------------- */
#define UNLOCKED(out, e) \
Py_BEGIN_ALLOW_THREADS \
out = (e); \
Py_END_ALLOW_THREADS
#define PRELOAD_UNLOCKED(_rc, _data, _size) \
Py_BEGIN_ALLOW_THREADS \
preload(_rc, _data, _size); \
Py_END_ALLOW_THREADS
/* ---------------- */
/* Argument parsing */
/* ---------------- */
#define OFFSET(k, y) offsetof(struct k, y)
#define SPECSIZE() (sizeof(argspec) / sizeof(argspec[0]))
enum arg_type {
ARG_DB, /** DbObject* */
ARG_TRANS, /** TransObject* */
ARG_ENV, /** EnvObject* */
ARG_OBJ, /** PyObject* */
ARG_BOOL, /** int */
ARG_BUF, /** MDB_val */
ARG_STR, /** char* */
ARG_INT, /** int */
ARG_SIZE /** size_t */
};
struct argspec {
const char *string;
unsigned short type;
unsigned short offset;
};
static PyTypeObject *type_tbl[] = {
&PyDatabase_Type,
&PyTransaction_Type,
&PyEnvironment_Type
};
static int NOINLINE
parse_ulong(PyObject *obj, uint64_t *l, PyObject *max)
{
int rc = PyObject_RichCompareBool(obj, py_zero, Py_GE);
if(rc == -1) {
return -1;
} else if(! rc) {
PyErr_Format(PyExc_OverflowError, "Integer argument must be >= 0");
return -1;
}
rc = PyObject_RichCompareBool(obj, max, Py_LE);
if(rc == -1) {
return -1;
} else if(! rc) {
PyErr_Format(PyExc_OverflowError, "Integer argument exceeds limit.");
return -1;
}
*l = PyLong_AsUnsignedLongLongMask(obj);
return 0;
}
/**
* Parse a single argument specified by `spec` into `out`, returning 0 on
* success or setting an exception and returning -1 on error.
*/
static int
parse_arg(const struct argspec *spec, PyObject *val, void *out)
{
void *dst = ((uint8_t *)out) + spec->offset;
int ret = 0;
uint64_t l;
if(val != Py_None) {
switch((enum arg_type) spec->type) {
case ARG_DB:
case ARG_TRANS:
case ARG_ENV:
if(val->ob_type != type_tbl[spec->type]) {
type_error("invalid type");
return -1;
}
/* fallthrough */
case ARG_OBJ:
*((PyObject **) dst) = val;
break;
case ARG_BOOL:
*((int *)dst) = PyObject_IsTrue(val);
break;
case ARG_BUF:
ret = val_from_buffer((MDB_val *)dst, val);
break;
case ARG_STR: {
MDB_val mv;
if(! (ret = val_from_buffer(&mv, val))) {
*((char **) dst) = mv.mv_data;
}
break;
}
case ARG_INT:
if(! (ret = parse_ulong(val, &l, py_int_max))) {
*((int *) dst) = (int)l;
}
break;
case ARG_SIZE:
if(! (ret = parse_ulong(val, &l, py_size_max))) {
*((size_t *) dst) = (size_t)l;
}
break;
}
}
return ret;
}
/**
* Walk `argspec`, building a Python dictionary mapping keyword arguments to a
* PyInt describing their offset in the array. Used to reduce keyword argument
* parsing from O(specsize) to O(number of supplied kwargs).
*/
static int NOINLINE
make_arg_cache(int specsize, const struct argspec *argspec, PyObject **cache)
{
Py_ssize_t i;
if(! ((*cache = PyDict_New()))) {
return -1;
}
for(i = 0; i < specsize; i++) {
const struct argspec *spec = argspec + i;
PyObject *key = PyUnicode_InternFromString(spec->string);
PyObject *val = MAKE_ID(i);
if((! (key && val)) || PyDict_SetItem(*cache, key, val)) {
return -1;
}
Py_DECREF(val);
}
return 0;
}
/**
* Like PyArg_ParseTupleAndKeywords except types are specialized for this
* module, keyword strings aren't dup'd every call and the code is >3x smaller.
*/
static int NOINLINE
parse_args(int valid, int specsize, const struct argspec *argspec,
PyObject **cache, PyObject *args, PyObject *kwds, void *out)
{
unsigned set = 0;
unsigned i;
if(! valid) {
err_invalid();
return -1;
}
if(args) {
Py_ssize_t size = PyTuple_GET_SIZE(args);
if(size > specsize) {
type_error("too many positional arguments.");
return -1;
}
if(specsize < size) {
size = specsize;
}
for(i = 0; i < size; i++) {
if(parse_arg(argspec + i, PyTuple_GET_ITEM(args, i), out)) {
return -1;
}
set |= 1 << i;
}
}
if(kwds) {
Py_ssize_t ppos = 0;
PyObject *pkey;
PyObject *pvalue;
if((! *cache) && make_arg_cache(specsize, argspec, cache)) {
return -1;
}
while(PyDict_Next(kwds, &ppos, &pkey, &pvalue)) {
PyObject *specidx;
int i;
if(! ((specidx = PyDict_GetItem(*cache, pkey)))) {
type_error("unrecognized keyword argument");
return -1;
}
i = READ_ID(specidx);
if(set & (1 << i)) {
PyErr_Format(PyExc_TypeError, "duplicate argument: %U", pkey);
return -1;
}
if(parse_arg(argspec + i, pvalue, out)) {
return -1;
}
}
}
return 0;
}
/**
* Return 1 if `db` is associated with the given `env`, otherwise raise an
* exception. Used to prevent DBIs from unrelated envs from being mixed
* together (which in future, would cause one env to access another's cursor
* pointers).
*/
static int
db_owner_check(DbObject *db, EnvObject *env)
{
if(db->env != env) {
err_set("Database handle belongs to another environment.", 0);
return 0;
}
return 1;
}
/* -------------------------------------------------------- */
/* Functionality shared between Transaction and Environment */
/* -------------------------------------------------------- */
static PyObject *
make_trans(EnvObject *env, DbObject *db, TransObject *parent, int write,
int buffers)
{
MDB_txn *parent_txn;
MDB_txn *txn;
TransObject *self;
int flags;
int rc;
DEBUG("make_trans(env=%p, parent=%p, write=%d, buffers=%d)",
env, parent, write, buffers)
if(! env->valid) {
return err_invalid();
}
if(! db) {
db = env->main_db;
} else if(! db_owner_check(db, env)) {
return NULL;
}
parent_txn = NULL;
if(parent) {
if(parent->flags & TRANS_RDONLY) {
return err_set("Read-only transactions cannot be nested.", EINVAL);
}
if(! parent->valid) {
return err_invalid();
}
parent_txn = parent->txn;
}
if(write && env->readonly) {
const char *msg =
"Cannot start write transaction with read-only environment.";
return err_set(msg, EACCES);
}
if((!write) && env->spare_txn) {
txn = env->spare_txn;
DEBUG("using cached txn", txn)
env->spare_txn = NULL;
UNLOCKED(rc, mdb_txn_renew(txn));
if(rc) {
mdb_txn_abort(txn);
return err_set("mdb_txn_renew", rc);
}
}
else {
flags = write ? 0 : MDB_RDONLY;
UNLOCKED(rc, mdb_txn_begin(env->env, parent_txn, flags, &txn));
if(rc) {
return err_set("mdb_txn_begin", rc);
}
}
if(! ((self = PyObject_New(TransObject, &PyTransaction_Type)))) {
mdb_txn_abort(txn);
return NULL;
}
self->txn = txn;
OBJECT_INIT(self)
LINK_CHILD(env, self)
self->weaklist = NULL;
self->env = env;
Py_INCREF(env);
self->db = db;
Py_INCREF(db);
#ifdef HAVE_MEMSINK
self->sink_head = NULL;
#endif
self->mutations = 0;
self->flags = 0;
if(! write) {
self->flags |= TRANS_RDONLY;
}
if(buffers) {
self->flags |= TRANS_BUFFERS;
}
return (PyObject *)self;
}
static PyObject *
make_cursor(DbObject *db, TransObject *trans)
{
CursorObject *self;
MDB_cursor *curs;
int rc;
if(! trans->valid) {
return err_invalid();
}
if(! db) {
db = trans->env->main_db;
} else if(! db_owner_check(db, trans->env)) {
return NULL;
}
UNLOCKED(rc, mdb_cursor_open(trans->txn, db->dbi, &curs));
if(rc) {
return err_set("mdb_cursor_open", rc);
}
self = PyObject_New(CursorObject, &PyCursor_Type);
if (!self) {
mdb_cursor_close(curs);
return NULL;
}
DEBUG("sizeof cursor = %d", (int) sizeof *self)
OBJECT_INIT(self)
LINK_CHILD(trans, self)
self->curs = curs;
self->positioned = 0;
self->key.mv_size = 0;
self->key.mv_data = NULL;
self->val.mv_size = 0;
self->val.mv_data = NULL;
self->trans = trans;
self->last_mutation = trans->mutations;
self->dbi_flags = db->flags;
Py_INCREF(self->trans);
return (PyObject *) self;
}
/* -------- */
/* Database */
/* -------- */
static DbObject *
db_from_name(EnvObject *env, MDB_txn *txn, const char *name,
unsigned int flags)
{
MDB_dbi dbi;
unsigned int f;
int rc;
DbObject *dbo;
UNLOCKED(rc, mdb_dbi_open(txn, name, flags, &dbi));
if(rc) {
err_set("mdb_dbi_open", rc);
return NULL;
}
if((rc = mdb_dbi_flags(txn, dbi, &f))) {
err_set("mdb_dbi_flags", rc);
mdb_dbi_close(env->env, dbi);
return NULL;
}
if(! ((dbo = PyObject_New(DbObject, &PyDatabase_Type)))) {
return NULL;
}
OBJECT_INIT(dbo)
LINK_CHILD(env, dbo)
dbo->env = env; /* no refcount */
dbo->dbi = dbi;
dbo->flags = f;
DEBUG("DbObject '%s' opened at %p", name, dbo)
return dbo;
}
/**
* Use a temporary transaction to manufacture a new _Database object for
* `name`.
*/
static DbObject *
txn_db_from_name(EnvObject *env, const char *name,
unsigned int flags)
{
int rc;
MDB_txn *txn;
DbObject *dbo;
int begin_flags = (name == NULL || env->readonly) ? MDB_RDONLY : 0;
UNLOCKED(rc, mdb_txn_begin(env->env, NULL, begin_flags, &txn));
if(rc) {
err_set("mdb_txn_begin", rc);
return NULL;
}
if(! ((dbo = db_from_name(env, txn, name, flags)))) {
Py_BEGIN_ALLOW_THREADS
mdb_txn_abort(txn);
Py_END_ALLOW_THREADS
return NULL;
}
UNLOCKED(rc, mdb_txn_commit(txn));
if(rc) {
Py_DECREF(dbo);
return err_set("mdb_txn_commit", rc);
}
return dbo;
}
static int
db_clear(DbObject *self)
{
if(self->env) {
UNLINK_CHILD(self->env, self)
self->env = NULL;
}
self->valid = 0;
return 0;
}
/**
* _Database.flags()
*/
static PyObject *
db_flags(DbObject *self, PyObject *args, PyObject *kwds)
{
PyObject *dct;