Coverage Report

Created: 2025-07-11 06:59

/src/Python-3.8.3/Python/getargs.c
Line
Count
Source (jump to first uncovered line)
1
2
/* New getargs implementation */
3
4
#include "Python.h"
5
#include "pycore_tupleobject.h"
6
7
#include <ctype.h>
8
#include <float.h>
9
10
11
#ifdef __cplusplus
12
extern "C" {
13
#endif
14
int PyArg_Parse(PyObject *, const char *, ...);
15
int PyArg_ParseTuple(PyObject *, const char *, ...);
16
int PyArg_VaParse(PyObject *, const char *, va_list);
17
18
int PyArg_ParseTupleAndKeywords(PyObject *, PyObject *,
19
                                const char *, char **, ...);
20
int PyArg_VaParseTupleAndKeywords(PyObject *, PyObject *,
21
                                const char *, char **, va_list);
22
23
int _PyArg_ParseTupleAndKeywordsFast(PyObject *, PyObject *,
24
                                            struct _PyArg_Parser *, ...);
25
int _PyArg_VaParseTupleAndKeywordsFast(PyObject *, PyObject *,
26
                                            struct _PyArg_Parser *, va_list);
27
28
#ifdef HAVE_DECLSPEC_DLL
29
/* Export functions */
30
PyAPI_FUNC(int) _PyArg_Parse_SizeT(PyObject *, const char *, ...);
31
PyAPI_FUNC(int) _PyArg_ParseStack_SizeT(PyObject *const *args, Py_ssize_t nargs,
32
                                        const char *format, ...);
33
PyAPI_FUNC(int) _PyArg_ParseStackAndKeywords_SizeT(PyObject *const *args, Py_ssize_t nargs,
34
                                        PyObject *kwnames,
35
                                        struct _PyArg_Parser *parser, ...);
36
PyAPI_FUNC(int) _PyArg_ParseTuple_SizeT(PyObject *, const char *, ...);
37
PyAPI_FUNC(int) _PyArg_ParseTupleAndKeywords_SizeT(PyObject *, PyObject *,
38
                                                  const char *, char **, ...);
39
PyAPI_FUNC(PyObject *) _Py_BuildValue_SizeT(const char *, ...);
40
PyAPI_FUNC(int) _PyArg_VaParse_SizeT(PyObject *, const char *, va_list);
41
PyAPI_FUNC(int) _PyArg_VaParseTupleAndKeywords_SizeT(PyObject *, PyObject *,
42
                                              const char *, char **, va_list);
43
44
PyAPI_FUNC(int) _PyArg_ParseTupleAndKeywordsFast_SizeT(PyObject *, PyObject *,
45
                                            struct _PyArg_Parser *, ...);
46
PyAPI_FUNC(int) _PyArg_VaParseTupleAndKeywordsFast_SizeT(PyObject *, PyObject *,
47
                                            struct _PyArg_Parser *, va_list);
48
#endif
49
50
34.7k
#define FLAG_COMPAT 1
51
14.1k
#define FLAG_SIZE_T 2
52
53
typedef int (*destr_t)(PyObject *, void *);
54
55
56
/* Keep track of "objects" that have been allocated or initialized and
57
   which will need to be deallocated or cleaned up somehow if overall
58
   parsing fails.
59
*/
60
typedef struct {
61
  void *item;
62
  destr_t destructor;
63
} freelistentry_t;
64
65
typedef struct {
66
  freelistentry_t *entries;
67
  int first_available;
68
  int entries_malloced;
69
} freelist_t;
70
71
14.7k
#define STATIC_FREELIST_ENTRIES 8
72
73
/* Forward */
74
static int vgetargs1_impl(PyObject *args, PyObject *const *stack, Py_ssize_t nargs,
75
                          const char *format, va_list *p_va, int flags);
76
static int vgetargs1(PyObject *, const char *, va_list *, int);
77
static void seterror(Py_ssize_t, const char *, int *, const char *, const char *);
78
static const char *convertitem(PyObject *, const char **, va_list *, int, int *,
79
                               char *, size_t, freelist_t *);
80
static const char *converttuple(PyObject *, const char **, va_list *, int,
81
                                int *, char *, size_t, int, freelist_t *);
82
static const char *convertsimple(PyObject *, const char **, va_list *, int,
83
                                 char *, size_t, freelist_t *);
84
static Py_ssize_t convertbuffer(PyObject *, const void **p, const char **);
85
static int getbuffer(PyObject *, Py_buffer *, const char**);
86
87
static int vgetargskeywords(PyObject *, PyObject *,
88
                            const char *, char **, va_list *, int);
89
static int vgetargskeywordsfast(PyObject *, PyObject *,
90
                            struct _PyArg_Parser *, va_list *, int);
91
static int vgetargskeywordsfast_impl(PyObject *const *args, Py_ssize_t nargs,
92
                          PyObject *keywords, PyObject *kwnames,
93
                          struct _PyArg_Parser *parser,
94
                          va_list *p_va, int flags);
95
static const char *skipitem(const char **, va_list *, int);
96
97
int
98
PyArg_Parse(PyObject *args, const char *format, ...)
99
0
{
100
0
    int retval;
101
0
    va_list va;
102
103
0
    va_start(va, format);
104
0
    retval = vgetargs1(args, format, &va, FLAG_COMPAT);
105
0
    va_end(va);
106
0
    return retval;
107
0
}
108
109
int
110
_PyArg_Parse_SizeT(PyObject *args, const char *format, ...)
111
0
{
112
0
    int retval;
113
0
    va_list va;
114
115
0
    va_start(va, format);
116
0
    retval = vgetargs1(args, format, &va, FLAG_COMPAT|FLAG_SIZE_T);
117
0
    va_end(va);
118
0
    return retval;
119
0
}
120
121
122
int
123
PyArg_ParseTuple(PyObject *args, const char *format, ...)
124
3.44k
{
125
3.44k
    int retval;
126
3.44k
    va_list va;
127
128
3.44k
    va_start(va, format);
129
3.44k
    retval = vgetargs1(args, format, &va, 0);
130
3.44k
    va_end(va);
131
3.44k
    return retval;
132
3.44k
}
133
134
int
135
_PyArg_ParseTuple_SizeT(PyObject *args, const char *format, ...)
136
8.15k
{
137
8.15k
    int retval;
138
8.15k
    va_list va;
139
140
8.15k
    va_start(va, format);
141
8.15k
    retval = vgetargs1(args, format, &va, FLAG_SIZE_T);
142
8.15k
    va_end(va);
143
8.15k
    return retval;
144
8.15k
}
145
146
147
int
148
_PyArg_ParseStack(PyObject *const *args, Py_ssize_t nargs, const char *format, ...)
149
0
{
150
0
    int retval;
151
0
    va_list va;
152
153
0
    va_start(va, format);
154
0
    retval = vgetargs1_impl(NULL, args, nargs, format, &va, 0);
155
0
    va_end(va);
156
0
    return retval;
157
0
}
158
159
int
160
_PyArg_ParseStack_SizeT(PyObject *const *args, Py_ssize_t nargs, const char *format, ...)
161
0
{
162
0
    int retval;
163
0
    va_list va;
164
165
0
    va_start(va, format);
166
0
    retval = vgetargs1_impl(NULL, args, nargs, format, &va, FLAG_SIZE_T);
167
0
    va_end(va);
168
0
    return retval;
169
0
}
170
171
172
int
173
PyArg_VaParse(PyObject *args, const char *format, va_list va)
174
0
{
175
0
    va_list lva;
176
0
    int retval;
177
178
0
    va_copy(lva, va);
179
180
0
    retval = vgetargs1(args, format, &lva, 0);
181
0
    va_end(lva);
182
0
    return retval;
183
0
}
184
185
int
186
_PyArg_VaParse_SizeT(PyObject *args, const char *format, va_list va)
187
0
{
188
0
    va_list lva;
189
0
    int retval;
190
191
0
    va_copy(lva, va);
192
193
0
    retval = vgetargs1(args, format, &lva, FLAG_SIZE_T);
194
0
    va_end(lva);
195
0
    return retval;
196
0
}
197
198
199
/* Handle cleanup of allocated memory in case of exception */
200
201
static int
202
cleanup_ptr(PyObject *self, void *ptr)
203
0
{
204
0
    if (ptr) {
205
0
        PyMem_FREE(ptr);
206
0
    }
207
0
    return 0;
208
0
}
209
210
static int
211
cleanup_buffer(PyObject *self, void *ptr)
212
0
{
213
0
    Py_buffer *buf = (Py_buffer *)ptr;
214
0
    if (buf) {
215
0
        PyBuffer_Release(buf);
216
0
    }
217
0
    return 0;
218
0
}
219
220
static int
221
addcleanup(void *ptr, freelist_t *freelist, destr_t destructor)
222
0
{
223
0
    int index;
224
225
0
    index = freelist->first_available;
226
0
    freelist->first_available += 1;
227
228
0
    freelist->entries[index].item = ptr;
229
0
    freelist->entries[index].destructor = destructor;
230
231
0
    return 0;
232
0
}
233
234
static int
235
cleanreturn(int retval, freelist_t *freelist)
236
14.7k
{
237
14.7k
    int index;
238
239
14.7k
    if (retval == 0) {
240
      /* A failure occurred, therefore execute all of the cleanup
241
         functions.
242
      */
243
260
      for (index = 0; index < freelist->first_available; ++index) {
244
0
          freelist->entries[index].destructor(NULL,
245
0
                                              freelist->entries[index].item);
246
0
      }
247
260
    }
248
14.7k
    if (freelist->entries_malloced)
249
0
        PyMem_FREE(freelist->entries);
250
14.7k
    return retval;
251
14.7k
}
252
253
254
static int
255
vgetargs1_impl(PyObject *compat_args, PyObject *const *stack, Py_ssize_t nargs, const char *format,
256
               va_list *p_va, int flags)
257
11.5k
{
258
11.5k
    char msgbuf[256];
259
11.5k
    int levels[32];
260
11.5k
    const char *fname = NULL;
261
11.5k
    const char *message = NULL;
262
11.5k
    int min = -1;
263
11.5k
    int max = 0;
264
11.5k
    int level = 0;
265
11.5k
    int endfmt = 0;
266
11.5k
    const char *formatsave = format;
267
11.5k
    Py_ssize_t i;
268
11.5k
    const char *msg;
269
11.5k
    int compat = flags & FLAG_COMPAT;
270
11.5k
    freelistentry_t static_entries[STATIC_FREELIST_ENTRIES];
271
11.5k
    freelist_t freelist;
272
273
11.5k
    assert(nargs == 0 || stack != NULL);
274
275
11.5k
    freelist.entries = static_entries;
276
11.5k
    freelist.first_available = 0;
277
11.5k
    freelist.entries_malloced = 0;
278
279
11.5k
    flags = flags & ~FLAG_COMPAT;
280
281
60.3k
    while (endfmt == 0) {
282
48.7k
        int c = *format++;
283
48.7k
        switch (c) {
284
0
        case '(':
285
0
            if (level == 0)
286
0
                max++;
287
0
            level++;
288
0
            if (level >= 30)
289
0
                Py_FatalError("too many tuple nesting levels "
290
0
                              "in argument format string");
291
0
            break;
292
0
        case ')':
293
0
            if (level == 0)
294
0
                Py_FatalError("excess ')' in getargs format");
295
0
            else
296
0
                level--;
297
0
            break;
298
702
        case '\0':
299
702
            endfmt = 1;
300
702
            break;
301
10.8k
        case ':':
302
10.8k
            fname = format;
303
10.8k
            endfmt = 1;
304
10.8k
            break;
305
0
        case ';':
306
0
            message = format;
307
0
            endfmt = 1;
308
0
            break;
309
3.12k
        case '|':
310
3.12k
            if (level == 0)
311
3.12k
                min = max;
312
3.12k
            break;
313
34.0k
        default:
314
34.0k
            if (level == 0) {
315
34.0k
                if (Py_ISALPHA(Py_CHARMASK(c)))
316
23.0k
                    if (c != 'e') /* skip encoded */
317
23.0k
                        max++;
318
34.0k
            }
319
34.0k
            break;
320
48.7k
        }
321
48.7k
    }
322
323
11.5k
    if (level != 0)
324
0
        Py_FatalError(/* '(' */ "missing ')' in getargs format");
325
326
11.5k
    if (min < 0)
327
8.47k
        min = max;
328
329
11.5k
    format = formatsave;
330
331
11.5k
    if (max > STATIC_FREELIST_ENTRIES) {
332
0
        freelist.entries = PyMem_NEW(freelistentry_t, max);
333
0
        if (freelist.entries == NULL) {
334
0
            PyErr_NoMemory();
335
0
            return 0;
336
0
        }
337
0
        freelist.entries_malloced = 1;
338
0
    }
339
340
11.5k
    if (compat) {
341
0
        if (max == 0) {
342
0
            if (compat_args == NULL)
343
0
                return 1;
344
0
            PyErr_Format(PyExc_TypeError,
345
0
                         "%.200s%s takes no arguments",
346
0
                         fname==NULL ? "function" : fname,
347
0
                         fname==NULL ? "" : "()");
348
0
            return cleanreturn(0, &freelist);
349
0
        }
350
0
        else if (min == 1 && max == 1) {
351
0
            if (compat_args == NULL) {
352
0
                PyErr_Format(PyExc_TypeError,
353
0
                             "%.200s%s takes at least one argument",
354
0
                             fname==NULL ? "function" : fname,
355
0
                             fname==NULL ? "" : "()");
356
0
                return cleanreturn(0, &freelist);
357
0
            }
358
0
            msg = convertitem(compat_args, &format, p_va, flags, levels,
359
0
                              msgbuf, sizeof(msgbuf), &freelist);
360
0
            if (msg == NULL)
361
0
                return cleanreturn(1, &freelist);
362
0
            seterror(levels[0], msg, levels+1, fname, message);
363
0
            return cleanreturn(0, &freelist);
364
0
        }
365
0
        else {
366
0
            PyErr_SetString(PyExc_SystemError,
367
0
                "old style getargs format uses new features");
368
0
            return cleanreturn(0, &freelist);
369
0
        }
370
0
    }
371
372
11.5k
    if (nargs < min || max < nargs) {
373
84
        if (message == NULL)
374
84
            PyErr_Format(PyExc_TypeError,
375
84
                         "%.150s%s takes %s %d argument%s (%zd given)",
376
84
                         fname==NULL ? "function" : fname,
377
84
                         fname==NULL ? "" : "()",
378
84
                         min==max ? "exactly"
379
84
                         : nargs < min ? "at least" : "at most",
380
84
                         nargs < min ? min : max,
381
84
                         (nargs < min ? min : max) == 1 ? "" : "s",
382
84
                         nargs);
383
0
        else
384
0
            PyErr_SetString(PyExc_TypeError, message);
385
84
        return cleanreturn(0, &freelist);
386
84
    }
387
388
31.1k
    for (i = 0; i < nargs; i++) {
389
19.6k
        if (*format == '|')
390
1.51k
            format++;
391
19.6k
        msg = convertitem(stack[i], &format, p_va,
392
19.6k
                          flags, levels, msgbuf,
393
19.6k
                          sizeof(msgbuf), &freelist);
394
19.6k
        if (msg) {
395
0
            seterror(i+1, msg, levels, fname, message);
396
0
            return cleanreturn(0, &freelist);
397
0
        }
398
19.6k
    }
399
400
11.5k
    if (*format != '\0' && !Py_ISALPHA(Py_CHARMASK(*format)) &&
401
11.5k
        *format != '(' &&
402
11.5k
        *format != '|' && *format != ':' && *format != ';') {
403
0
        PyErr_Format(PyExc_SystemError,
404
0
                     "bad format string: %.200s", formatsave);
405
0
        return cleanreturn(0, &freelist);
406
0
    }
407
408
11.5k
    return cleanreturn(1, &freelist);
409
11.5k
}
410
411
static int
412
vgetargs1(PyObject *args, const char *format, va_list *p_va, int flags)
413
11.5k
{
414
11.5k
    PyObject **stack;
415
11.5k
    Py_ssize_t nargs;
416
417
11.5k
    if (!(flags & FLAG_COMPAT)) {
418
11.5k
        assert(args != NULL);
419
420
11.5k
        if (!PyTuple_Check(args)) {
421
0
            PyErr_SetString(PyExc_SystemError,
422
0
                "new style getargs format but argument is not a tuple");
423
0
            return 0;
424
0
        }
425
426
11.5k
        stack = _PyTuple_ITEMS(args);
427
11.5k
        nargs = PyTuple_GET_SIZE(args);
428
11.5k
    }
429
0
    else {
430
0
        stack = NULL;
431
0
        nargs = 0;
432
0
    }
433
434
11.5k
    return vgetargs1_impl(args, stack, nargs, format, p_va, flags);
435
11.5k
}
436
437
438
static void
439
seterror(Py_ssize_t iarg, const char *msg, int *levels, const char *fname,
440
         const char *message)
441
0
{
442
0
    char buf[512];
443
0
    int i;
444
0
    char *p = buf;
445
446
0
    if (PyErr_Occurred())
447
0
        return;
448
0
    else if (message == NULL) {
449
0
        if (fname != NULL) {
450
0
            PyOS_snprintf(p, sizeof(buf), "%.200s() ", fname);
451
0
            p += strlen(p);
452
0
        }
453
0
        if (iarg != 0) {
454
0
            PyOS_snprintf(p, sizeof(buf) - (p - buf),
455
0
                          "argument %" PY_FORMAT_SIZE_T "d", iarg);
456
0
            i = 0;
457
0
            p += strlen(p);
458
0
            while (i < 32 && levels[i] > 0 && (int)(p-buf) < 220) {
459
0
                PyOS_snprintf(p, sizeof(buf) - (p - buf),
460
0
                              ", item %d", levels[i]-1);
461
0
                p += strlen(p);
462
0
                i++;
463
0
            }
464
0
        }
465
0
        else {
466
0
            PyOS_snprintf(p, sizeof(buf) - (p - buf), "argument");
467
0
            p += strlen(p);
468
0
        }
469
0
        PyOS_snprintf(p, sizeof(buf) - (p - buf), " %.256s", msg);
470
0
        message = buf;
471
0
    }
472
0
    if (msg[0] == '(') {
473
0
        PyErr_SetString(PyExc_SystemError, message);
474
0
    }
475
0
    else {
476
0
        PyErr_SetString(PyExc_TypeError, message);
477
0
    }
478
0
}
479
480
481
/* Convert a tuple argument.
482
   On entry, *p_format points to the character _after_ the opening '('.
483
   On successful exit, *p_format points to the closing ')'.
484
   If successful:
485
      *p_format and *p_va are updated,
486
      *levels and *msgbuf are untouched,
487
      and NULL is returned.
488
   If the argument is invalid:
489
      *p_format is unchanged,
490
      *p_va is undefined,
491
      *levels is a 0-terminated list of item numbers,
492
      *msgbuf contains an error message, whose format is:
493
     "must be <typename1>, not <typename2>", where:
494
        <typename1> is the name of the expected type, and
495
        <typename2> is the name of the actual type,
496
      and msgbuf is returned.
497
*/
498
499
static const char *
500
converttuple(PyObject *arg, const char **p_format, va_list *p_va, int flags,
501
             int *levels, char *msgbuf, size_t bufsize, int toplevel,
502
             freelist_t *freelist)
503
0
{
504
0
    int level = 0;
505
0
    int n = 0;
506
0
    const char *format = *p_format;
507
0
    int i;
508
0
    Py_ssize_t len;
509
510
0
    for (;;) {
511
0
        int c = *format++;
512
0
        if (c == '(') {
513
0
            if (level == 0)
514
0
                n++;
515
0
            level++;
516
0
        }
517
0
        else if (c == ')') {
518
0
            if (level == 0)
519
0
                break;
520
0
            level--;
521
0
        }
522
0
        else if (c == ':' || c == ';' || c == '\0')
523
0
            break;
524
0
        else if (level == 0 && Py_ISALPHA(Py_CHARMASK(c)))
525
0
            n++;
526
0
    }
527
528
0
    if (!PySequence_Check(arg) || PyBytes_Check(arg)) {
529
0
        levels[0] = 0;
530
0
        PyOS_snprintf(msgbuf, bufsize,
531
0
                      toplevel ? "expected %d arguments, not %.50s" :
532
0
                      "must be %d-item sequence, not %.50s",
533
0
                  n,
534
0
                  arg == Py_None ? "None" : arg->ob_type->tp_name);
535
0
        return msgbuf;
536
0
    }
537
538
0
    len = PySequence_Size(arg);
539
0
    if (len != n) {
540
0
        levels[0] = 0;
541
0
        if (toplevel) {
542
0
            PyOS_snprintf(msgbuf, bufsize,
543
0
                          "expected %d argument%s, not %" PY_FORMAT_SIZE_T "d",
544
0
                          n,
545
0
                          n == 1 ? "" : "s",
546
0
                          len);
547
0
        }
548
0
        else {
549
0
            PyOS_snprintf(msgbuf, bufsize,
550
0
                          "must be sequence of length %d, "
551
0
                          "not %" PY_FORMAT_SIZE_T "d",
552
0
                          n, len);
553
0
        }
554
0
        return msgbuf;
555
0
    }
556
557
0
    format = *p_format;
558
0
    for (i = 0; i < n; i++) {
559
0
        const char *msg;
560
0
        PyObject *item;
561
0
        item = PySequence_GetItem(arg, i);
562
0
        if (item == NULL) {
563
0
            PyErr_Clear();
564
0
            levels[0] = i+1;
565
0
            levels[1] = 0;
566
0
            strncpy(msgbuf, "is not retrievable", bufsize);
567
0
            return msgbuf;
568
0
        }
569
0
        msg = convertitem(item, &format, p_va, flags, levels+1,
570
0
                          msgbuf, bufsize, freelist);
571
        /* PySequence_GetItem calls tp->sq_item, which INCREFs */
572
0
        Py_XDECREF(item);
573
0
        if (msg != NULL) {
574
0
            levels[0] = i+1;
575
0
            return msg;
576
0
        }
577
0
    }
578
579
0
    *p_format = format;
580
0
    return NULL;
581
0
}
582
583
584
/* Convert a single item. */
585
586
static const char *
587
convertitem(PyObject *arg, const char **p_format, va_list *p_va, int flags,
588
            int *levels, char *msgbuf, size_t bufsize, freelist_t *freelist)
589
23.9k
{
590
23.9k
    const char *msg;
591
23.9k
    const char *format = *p_format;
592
593
23.9k
    if (*format == '(' /* ')' */) {
594
0
        format++;
595
0
        msg = converttuple(arg, &format, p_va, flags, levels, msgbuf,
596
0
                           bufsize, 0, freelist);
597
0
        if (msg == NULL)
598
0
            format++;
599
0
    }
600
23.9k
    else {
601
23.9k
        msg = convertsimple(arg, &format, p_va, flags,
602
23.9k
                            msgbuf, bufsize, freelist);
603
23.9k
        if (msg != NULL)
604
0
            levels[0] = 0;
605
23.9k
    }
606
23.9k
    if (msg == NULL)
607
23.9k
        *p_format = format;
608
23.9k
    return msg;
609
23.9k
}
610
611
612
613
/* Format an error message generated by convertsimple().
614
   displayname must be UTF-8 encoded.
615
*/
616
617
void
618
_PyArg_BadArgument(const char *fname, const char *displayname,
619
                   const char *expected, PyObject *arg)
620
0
{
621
0
    PyErr_Format(PyExc_TypeError,
622
0
                 "%.200s() %.200s must be %.50s, not %.50s",
623
0
                 fname, displayname, expected,
624
0
                 arg == Py_None ? "None" : arg->ob_type->tp_name);
625
0
}
626
627
static const char *
628
converterr(const char *expected, PyObject *arg, char *msgbuf, size_t bufsize)
629
0
{
630
0
    assert(expected != NULL);
631
0
    assert(arg != NULL);
632
0
    if (expected[0] == '(') {
633
0
        PyOS_snprintf(msgbuf, bufsize,
634
0
                      "%.100s", expected);
635
0
    }
636
0
    else {
637
0
        PyOS_snprintf(msgbuf, bufsize,
638
0
                      "must be %.50s, not %.50s", expected,
639
0
                      arg == Py_None ? "None" : arg->ob_type->tp_name);
640
0
    }
641
0
    return msgbuf;
642
0
}
643
644
0
#define CONV_UNICODE "(unicode conversion error)"
645
646
/* Explicitly check for float arguments when integers are expected.
647
   Return 1 for error, 0 if ok.
648
   XXX Should be removed after the end of the deprecation period in
649
   _PyLong_FromNbIndexOrNbInt. */
650
static int
651
float_argument_error(PyObject *arg)
652
2.09k
{
653
2.09k
    if (PyFloat_Check(arg)) {
654
0
        PyErr_SetString(PyExc_TypeError,
655
0
                        "integer argument expected, got float" );
656
0
        return 1;
657
0
    }
658
2.09k
    else
659
2.09k
        return 0;
660
2.09k
}
661
662
/* Convert a non-tuple argument.  Return NULL if conversion went OK,
663
   or a string with a message describing the failure.  The message is
664
   formatted as "must be <desired type>, not <actual type>".
665
   When failing, an exception may or may not have been raised.
666
   Don't call if a tuple is expected.
667
668
   When you add new format codes, please don't forget poor skipitem() below.
669
*/
670
671
static const char *
672
convertsimple(PyObject *arg, const char **p_format, va_list *p_va, int flags,
673
              char *msgbuf, size_t bufsize, freelist_t *freelist)
674
23.9k
{
675
    /* For # codes */
676
23.9k
#define FETCH_SIZE      int *q=NULL;Py_ssize_t *q2=NULL;\
677
2.42k
    if (flags & FLAG_SIZE_T) q2=va_arg(*p_va, Py_ssize_t*); \
678
2.42k
    else { \
679
0
        if (PyErr_WarnEx(PyExc_DeprecationWarning, \
680
0
                    "PY_SSIZE_T_CLEAN will be required for '#' formats", 1)) { \
681
0
            return NULL; \
682
0
        } \
683
0
        q=va_arg(*p_va, int*); \
684
0
    }
685
23.9k
#define STORE_SIZE(s)   \
686
23.9k
    if (flags & FLAG_SIZE_T) \
687
2.42k
        *q2=s; \
688
2.42k
    else { \
689
0
        if (INT_MAX < s) { \
690
0
            PyErr_SetString(PyExc_OverflowError, \
691
0
                "size does not fit in an int"); \
692
0
            return converterr("", arg, msgbuf, bufsize); \
693
0
        } \
694
0
        *q = (int)s; \
695
0
    }
696
23.9k
#define BUFFER_LEN      ((flags & FLAG_SIZE_T) ? *q2:*q)
697
23.9k
#define RETURN_ERR_OCCURRED return msgbuf
698
699
23.9k
    const char *format = *p_format;
700
23.9k
    char c = *format++;
701
23.9k
    const char *sarg;
702
703
23.9k
    switch (c) {
704
705
0
    case 'b': { /* unsigned byte -- very short int */
706
0
        char *p = va_arg(*p_va, char *);
707
0
        long ival;
708
0
        if (float_argument_error(arg))
709
0
            RETURN_ERR_OCCURRED;
710
0
        ival = PyLong_AsLong(arg);
711
0
        if (ival == -1 && PyErr_Occurred())
712
0
            RETURN_ERR_OCCURRED;
713
0
        else if (ival < 0) {
714
0
            PyErr_SetString(PyExc_OverflowError,
715
0
                            "unsigned byte integer is less than minimum");
716
0
            RETURN_ERR_OCCURRED;
717
0
        }
718
0
        else if (ival > UCHAR_MAX) {
719
0
            PyErr_SetString(PyExc_OverflowError,
720
0
                            "unsigned byte integer is greater than maximum");
721
0
            RETURN_ERR_OCCURRED;
722
0
        }
723
0
        else
724
0
            *p = (unsigned char) ival;
725
0
        break;
726
0
    }
727
728
0
    case 'B': {/* byte sized bitfield - both signed and unsigned
729
                  values allowed */
730
0
        char *p = va_arg(*p_va, char *);
731
0
        long ival;
732
0
        if (float_argument_error(arg))
733
0
            RETURN_ERR_OCCURRED;
734
0
        ival = PyLong_AsUnsignedLongMask(arg);
735
0
        if (ival == -1 && PyErr_Occurred())
736
0
            RETURN_ERR_OCCURRED;
737
0
        else
738
0
            *p = (unsigned char) ival;
739
0
        break;
740
0
    }
741
742
0
    case 'h': {/* signed short int */
743
0
        short *p = va_arg(*p_va, short *);
744
0
        long ival;
745
0
        if (float_argument_error(arg))
746
0
            RETURN_ERR_OCCURRED;
747
0
        ival = PyLong_AsLong(arg);
748
0
        if (ival == -1 && PyErr_Occurred())
749
0
            RETURN_ERR_OCCURRED;
750
0
        else if (ival < SHRT_MIN) {
751
0
            PyErr_SetString(PyExc_OverflowError,
752
0
                            "signed short integer is less than minimum");
753
0
            RETURN_ERR_OCCURRED;
754
0
        }
755
0
        else if (ival > SHRT_MAX) {
756
0
            PyErr_SetString(PyExc_OverflowError,
757
0
                            "signed short integer is greater than maximum");
758
0
            RETURN_ERR_OCCURRED;
759
0
        }
760
0
        else
761
0
            *p = (short) ival;
762
0
        break;
763
0
    }
764
765
0
    case 'H': { /* short int sized bitfield, both signed and
766
                   unsigned allowed */
767
0
        unsigned short *p = va_arg(*p_va, unsigned short *);
768
0
        long ival;
769
0
        if (float_argument_error(arg))
770
0
            RETURN_ERR_OCCURRED;
771
0
        ival = PyLong_AsUnsignedLongMask(arg);
772
0
        if (ival == -1 && PyErr_Occurred())
773
0
            RETURN_ERR_OCCURRED;
774
0
        else
775
0
            *p = (unsigned short) ival;
776
0
        break;
777
0
    }
778
779
860
    case 'i': {/* signed int */
780
860
        int *p = va_arg(*p_va, int *);
781
860
        long ival;
782
860
        if (float_argument_error(arg))
783
0
            RETURN_ERR_OCCURRED;
784
860
        ival = PyLong_AsLong(arg);
785
860
        if (ival == -1 && PyErr_Occurred())
786
0
            RETURN_ERR_OCCURRED;
787
860
        else if (ival > INT_MAX) {
788
0
            PyErr_SetString(PyExc_OverflowError,
789
0
                            "signed integer is greater than maximum");
790
0
            RETURN_ERR_OCCURRED;
791
0
        }
792
860
        else if (ival < INT_MIN) {
793
0
            PyErr_SetString(PyExc_OverflowError,
794
0
                            "signed integer is less than minimum");
795
0
            RETURN_ERR_OCCURRED;
796
0
        }
797
860
        else
798
860
            *p = ival;
799
860
        break;
800
860
    }
801
802
860
    case 'I': { /* int sized bitfield, both signed and
803
                   unsigned allowed */
804
0
        unsigned int *p = va_arg(*p_va, unsigned int *);
805
0
        unsigned int ival;
806
0
        if (float_argument_error(arg))
807
0
            RETURN_ERR_OCCURRED;
808
0
        ival = (unsigned int)PyLong_AsUnsignedLongMask(arg);
809
0
        if (ival == (unsigned int)-1 && PyErr_Occurred())
810
0
            RETURN_ERR_OCCURRED;
811
0
        else
812
0
            *p = ival;
813
0
        break;
814
0
    }
815
816
1.23k
    case 'n': /* Py_ssize_t */
817
1.23k
    {
818
1.23k
        PyObject *iobj;
819
1.23k
        Py_ssize_t *p = va_arg(*p_va, Py_ssize_t *);
820
1.23k
        Py_ssize_t ival = -1;
821
1.23k
        if (float_argument_error(arg))
822
0
            RETURN_ERR_OCCURRED;
823
1.23k
        iobj = PyNumber_Index(arg);
824
1.23k
        if (iobj != NULL) {
825
1.23k
            ival = PyLong_AsSsize_t(iobj);
826
1.23k
            Py_DECREF(iobj);
827
1.23k
        }
828
1.23k
        if (ival == -1 && PyErr_Occurred())
829
0
            RETURN_ERR_OCCURRED;
830
1.23k
        *p = ival;
831
1.23k
        break;
832
1.23k
    }
833
0
    case 'l': {/* long int */
834
0
        long *p = va_arg(*p_va, long *);
835
0
        long ival;
836
0
        if (float_argument_error(arg))
837
0
            RETURN_ERR_OCCURRED;
838
0
        ival = PyLong_AsLong(arg);
839
0
        if (ival == -1 && PyErr_Occurred())
840
0
            RETURN_ERR_OCCURRED;
841
0
        else
842
0
            *p = ival;
843
0
        break;
844
0
    }
845
846
0
    case 'k': { /* long sized bitfield */
847
0
        unsigned long *p = va_arg(*p_va, unsigned long *);
848
0
        unsigned long ival;
849
0
        if (PyLong_Check(arg))
850
0
            ival = PyLong_AsUnsignedLongMask(arg);
851
0
        else
852
0
            return converterr("int", arg, msgbuf, bufsize);
853
0
        *p = ival;
854
0
        break;
855
0
    }
856
857
0
    case 'L': {/* long long */
858
0
        long long *p = va_arg( *p_va, long long * );
859
0
        long long ival;
860
0
        if (float_argument_error(arg))
861
0
            RETURN_ERR_OCCURRED;
862
0
        ival = PyLong_AsLongLong(arg);
863
0
        if (ival == (long long)-1 && PyErr_Occurred())
864
0
            RETURN_ERR_OCCURRED;
865
0
        else
866
0
            *p = ival;
867
0
        break;
868
0
    }
869
870
0
    case 'K': { /* long long sized bitfield */
871
0
        unsigned long long *p = va_arg(*p_va, unsigned long long *);
872
0
        unsigned long long ival;
873
0
        if (PyLong_Check(arg))
874
0
            ival = PyLong_AsUnsignedLongLongMask(arg);
875
0
        else
876
0
            return converterr("int", arg, msgbuf, bufsize);
877
0
        *p = ival;
878
0
        break;
879
0
    }
880
881
0
    case 'f': {/* float */
882
0
        float *p = va_arg(*p_va, float *);
883
0
        double dval = PyFloat_AsDouble(arg);
884
0
        if (dval == -1.0 && PyErr_Occurred())
885
0
            RETURN_ERR_OCCURRED;
886
0
        else
887
0
            *p = (float) dval;
888
0
        break;
889
0
    }
890
891
0
    case 'd': {/* double */
892
0
        double *p = va_arg(*p_va, double *);
893
0
        double dval = PyFloat_AsDouble(arg);
894
0
        if (dval == -1.0 && PyErr_Occurred())
895
0
            RETURN_ERR_OCCURRED;
896
0
        else
897
0
            *p = dval;
898
0
        break;
899
0
    }
900
901
0
    case 'D': {/* complex double */
902
0
        Py_complex *p = va_arg(*p_va, Py_complex *);
903
0
        Py_complex cval;
904
0
        cval = PyComplex_AsCComplex(arg);
905
0
        if (PyErr_Occurred())
906
0
            RETURN_ERR_OCCURRED;
907
0
        else
908
0
            *p = cval;
909
0
        break;
910
0
    }
911
912
0
    case 'c': {/* char */
913
0
        char *p = va_arg(*p_va, char *);
914
0
        if (PyBytes_Check(arg) && PyBytes_Size(arg) == 1)
915
0
            *p = PyBytes_AS_STRING(arg)[0];
916
0
        else if (PyByteArray_Check(arg) && PyByteArray_Size(arg) == 1)
917
0
            *p = PyByteArray_AS_STRING(arg)[0];
918
0
        else
919
0
            return converterr("a byte string of length 1", arg, msgbuf, bufsize);
920
0
        break;
921
0
    }
922
923
0
    case 'C': {/* unicode char */
924
0
        int *p = va_arg(*p_va, int *);
925
0
        int kind;
926
0
        void *data;
927
928
0
        if (!PyUnicode_Check(arg))
929
0
            return converterr("a unicode character", arg, msgbuf, bufsize);
930
931
0
        if (PyUnicode_READY(arg))
932
0
            RETURN_ERR_OCCURRED;
933
934
0
        if (PyUnicode_GET_LENGTH(arg) != 1)
935
0
            return converterr("a unicode character", arg, msgbuf, bufsize);
936
937
0
        kind = PyUnicode_KIND(arg);
938
0
        data = PyUnicode_DATA(arg);
939
0
        *p = PyUnicode_READ(kind, data, 0);
940
0
        break;
941
0
    }
942
943
1
    case 'p': {/* boolean *p*redicate */
944
1
        int *p = va_arg(*p_va, int *);
945
1
        int val = PyObject_IsTrue(arg);
946
1
        if (val > 0)
947
0
            *p = 1;
948
1
        else if (val == 0)
949
1
            *p = 0;
950
0
        else
951
0
            RETURN_ERR_OCCURRED;
952
1
        break;
953
1
    }
954
955
    /* XXX WAAAAH!  's', 'y', 'z', 'u', 'Z', 'e', 'w' codes all
956
       need to be cleaned up! */
957
958
2.42k
    case 'y': {/* any bytes-like object */
959
2.42k
        void **p = (void **)va_arg(*p_va, char **);
960
2.42k
        const char *buf;
961
2.42k
        Py_ssize_t count;
962
2.42k
        if (*format == '*') {
963
0
            if (getbuffer(arg, (Py_buffer*)p, &buf) < 0)
964
0
                return converterr(buf, arg, msgbuf, bufsize);
965
0
            format++;
966
0
            if (addcleanup(p, freelist, cleanup_buffer)) {
967
0
                return converterr(
968
0
                    "(cleanup problem)",
969
0
                    arg, msgbuf, bufsize);
970
0
            }
971
0
            break;
972
0
        }
973
2.42k
        count = convertbuffer(arg, (const void **)p, &buf);
974
2.42k
        if (count < 0)
975
0
            return converterr(buf, arg, msgbuf, bufsize);
976
2.42k
        if (*format == '#') {
977
2.42k
            FETCH_SIZE;
978
2.42k
            STORE_SIZE(count);
979
2.42k
            format++;
980
2.42k
        } else {
981
0
            if (strlen(*p) != (size_t)count) {
982
0
                PyErr_SetString(PyExc_ValueError, "embedded null byte");
983
0
                RETURN_ERR_OCCURRED;
984
0
            }
985
0
        }
986
2.42k
        break;
987
2.42k
    }
988
989
2.42k
    case 's': /* text string or bytes-like object */
990
1
    case 'z': /* text string, bytes-like object or None */
991
1
    {
992
1
        if (*format == '*') {
993
            /* "s*" or "z*" */
994
0
            Py_buffer *p = (Py_buffer *)va_arg(*p_va, Py_buffer *);
995
996
0
            if (c == 'z' && arg == Py_None)
997
0
                PyBuffer_FillInfo(p, NULL, NULL, 0, 1, 0);
998
0
            else if (PyUnicode_Check(arg)) {
999
0
                Py_ssize_t len;
1000
0
                sarg = PyUnicode_AsUTF8AndSize(arg, &len);
1001
0
                if (sarg == NULL)
1002
0
                    return converterr(CONV_UNICODE,
1003
0
                                      arg, msgbuf, bufsize);
1004
0
                PyBuffer_FillInfo(p, arg, (void *)sarg, len, 1, 0);
1005
0
            }
1006
0
            else { /* any bytes-like object */
1007
0
                const char *buf;
1008
0
                if (getbuffer(arg, p, &buf) < 0)
1009
0
                    return converterr(buf, arg, msgbuf, bufsize);
1010
0
            }
1011
0
            if (addcleanup(p, freelist, cleanup_buffer)) {
1012
0
                return converterr(
1013
0
                    "(cleanup problem)",
1014
0
                    arg, msgbuf, bufsize);
1015
0
            }
1016
0
            format++;
1017
1
        } else if (*format == '#') { /* a string or read-only bytes-like object */
1018
            /* "s#" or "z#" */
1019
0
            const void **p = (const void **)va_arg(*p_va, const char **);
1020
0
            FETCH_SIZE;
1021
1022
0
            if (c == 'z' && arg == Py_None) {
1023
0
                *p = NULL;
1024
0
                STORE_SIZE(0);
1025
0
            }
1026
0
            else if (PyUnicode_Check(arg)) {
1027
0
                Py_ssize_t len;
1028
0
                sarg = PyUnicode_AsUTF8AndSize(arg, &len);
1029
0
                if (sarg == NULL)
1030
0
                    return converterr(CONV_UNICODE,
1031
0
                                      arg, msgbuf, bufsize);
1032
0
                *p = sarg;
1033
0
                STORE_SIZE(len);
1034
0
            }
1035
0
            else { /* read-only bytes-like object */
1036
                /* XXX Really? */
1037
0
                const char *buf;
1038
0
                Py_ssize_t count = convertbuffer(arg, p, &buf);
1039
0
                if (count < 0)
1040
0
                    return converterr(buf, arg, msgbuf, bufsize);
1041
0
                STORE_SIZE(count);
1042
0
            }
1043
0
            format++;
1044
1
        } else {
1045
            /* "s" or "z" */
1046
1
            const char **p = va_arg(*p_va, const char **);
1047
1
            Py_ssize_t len;
1048
1
            sarg = NULL;
1049
1050
1
            if (c == 'z' && arg == Py_None)
1051
0
                *p = NULL;
1052
1
            else if (PyUnicode_Check(arg)) {
1053
1
                sarg = PyUnicode_AsUTF8AndSize(arg, &len);
1054
1
                if (sarg == NULL)
1055
0
                    return converterr(CONV_UNICODE,
1056
0
                                      arg, msgbuf, bufsize);
1057
1
                if (strlen(sarg) != (size_t)len) {
1058
0
                    PyErr_SetString(PyExc_ValueError, "embedded null character");
1059
0
                    RETURN_ERR_OCCURRED;
1060
0
                }
1061
1
                *p = sarg;
1062
1
            }
1063
0
            else
1064
0
                return converterr(c == 'z' ? "str or None" : "str",
1065
0
                                  arg, msgbuf, bufsize);
1066
1
        }
1067
1
        break;
1068
1
    }
1069
1070
1
    case 'u': /* raw unicode buffer (Py_UNICODE *) */
1071
0
    case 'Z': /* raw unicode buffer or None */
1072
0
    {
1073
0
        Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **);
1074
1075
0
        if (*format == '#') {
1076
            /* "u#" or "Z#" */
1077
0
            FETCH_SIZE;
1078
1079
0
            if (c == 'Z' && arg == Py_None) {
1080
0
                *p = NULL;
1081
0
                STORE_SIZE(0);
1082
0
            }
1083
0
            else if (PyUnicode_Check(arg)) {
1084
0
                Py_ssize_t len;
1085
0
                *p = PyUnicode_AsUnicodeAndSize(arg, &len);
1086
0
                if (*p == NULL)
1087
0
                    RETURN_ERR_OCCURRED;
1088
0
                STORE_SIZE(len);
1089
0
            }
1090
0
            else
1091
0
                return converterr(c == 'Z' ? "str or None" : "str",
1092
0
                                  arg, msgbuf, bufsize);
1093
0
            format++;
1094
0
        } else {
1095
            /* "u" or "Z" */
1096
0
            if (c == 'Z' && arg == Py_None)
1097
0
                *p = NULL;
1098
0
            else if (PyUnicode_Check(arg)) {
1099
0
                Py_ssize_t len;
1100
0
                *p = PyUnicode_AsUnicodeAndSize(arg, &len);
1101
0
                if (*p == NULL)
1102
0
                    RETURN_ERR_OCCURRED;
1103
0
                if (wcslen(*p) != (size_t)len) {
1104
0
                    PyErr_SetString(PyExc_ValueError, "embedded null character");
1105
0
                    RETURN_ERR_OCCURRED;
1106
0
                }
1107
0
            } else
1108
0
                return converterr(c == 'Z' ? "str or None" : "str",
1109
0
                                  arg, msgbuf, bufsize);
1110
0
        }
1111
0
        break;
1112
0
    }
1113
1114
0
    case 'e': {/* encoded string */
1115
0
        char **buffer;
1116
0
        const char *encoding;
1117
0
        PyObject *s;
1118
0
        int recode_strings;
1119
0
        Py_ssize_t size;
1120
0
        const char *ptr;
1121
1122
        /* Get 'e' parameter: the encoding name */
1123
0
        encoding = (const char *)va_arg(*p_va, const char *);
1124
0
        if (encoding == NULL)
1125
0
            encoding = PyUnicode_GetDefaultEncoding();
1126
1127
        /* Get output buffer parameter:
1128
           's' (recode all objects via Unicode) or
1129
           't' (only recode non-string objects)
1130
        */
1131
0
        if (*format == 's')
1132
0
            recode_strings = 1;
1133
0
        else if (*format == 't')
1134
0
            recode_strings = 0;
1135
0
        else
1136
0
            return converterr(
1137
0
                "(unknown parser marker combination)",
1138
0
                arg, msgbuf, bufsize);
1139
0
        buffer = (char **)va_arg(*p_va, char **);
1140
0
        format++;
1141
0
        if (buffer == NULL)
1142
0
            return converterr("(buffer is NULL)",
1143
0
                              arg, msgbuf, bufsize);
1144
1145
        /* Encode object */
1146
0
        if (!recode_strings &&
1147
0
            (PyBytes_Check(arg) || PyByteArray_Check(arg))) {
1148
0
            s = arg;
1149
0
            Py_INCREF(s);
1150
0
            if (PyBytes_Check(arg)) {
1151
0
                size = PyBytes_GET_SIZE(s);
1152
0
                ptr = PyBytes_AS_STRING(s);
1153
0
            }
1154
0
            else {
1155
0
                size = PyByteArray_GET_SIZE(s);
1156
0
                ptr = PyByteArray_AS_STRING(s);
1157
0
            }
1158
0
        }
1159
0
        else if (PyUnicode_Check(arg)) {
1160
            /* Encode object; use default error handling */
1161
0
            s = PyUnicode_AsEncodedString(arg,
1162
0
                                          encoding,
1163
0
                                          NULL);
1164
0
            if (s == NULL)
1165
0
                return converterr("(encoding failed)",
1166
0
                                  arg, msgbuf, bufsize);
1167
0
            assert(PyBytes_Check(s));
1168
0
            size = PyBytes_GET_SIZE(s);
1169
0
            ptr = PyBytes_AS_STRING(s);
1170
0
            if (ptr == NULL)
1171
0
                ptr = "";
1172
0
        }
1173
0
        else {
1174
0
            return converterr(
1175
0
                recode_strings ? "str" : "str, bytes or bytearray",
1176
0
                arg, msgbuf, bufsize);
1177
0
        }
1178
1179
        /* Write output; output is guaranteed to be 0-terminated */
1180
0
        if (*format == '#') {
1181
            /* Using buffer length parameter '#':
1182
1183
               - if *buffer is NULL, a new buffer of the
1184
               needed size is allocated and the data
1185
               copied into it; *buffer is updated to point
1186
               to the new buffer; the caller is
1187
               responsible for PyMem_Free()ing it after
1188
               usage
1189
1190
               - if *buffer is not NULL, the data is
1191
               copied to *buffer; *buffer_len has to be
1192
               set to the size of the buffer on input;
1193
               buffer overflow is signalled with an error;
1194
               buffer has to provide enough room for the
1195
               encoded string plus the trailing 0-byte
1196
1197
               - in both cases, *buffer_len is updated to
1198
               the size of the buffer /excluding/ the
1199
               trailing 0-byte
1200
1201
            */
1202
0
            int *q = NULL; Py_ssize_t *q2 = NULL;
1203
0
            if (flags & FLAG_SIZE_T) {
1204
0
                q2 = va_arg(*p_va, Py_ssize_t*);
1205
0
            }
1206
0
            else {
1207
0
                if (PyErr_WarnEx(PyExc_DeprecationWarning,
1208
0
                            "PY_SSIZE_T_CLEAN will be required for '#' formats", 1))
1209
0
                {
1210
0
                    Py_DECREF(s);
1211
0
                    return NULL;
1212
0
                }
1213
0
                q = va_arg(*p_va, int*);
1214
0
            }
1215
1216
0
            format++;
1217
0
            if (q == NULL && q2 == NULL) {
1218
0
                Py_DECREF(s);
1219
0
                return converterr(
1220
0
                    "(buffer_len is NULL)",
1221
0
                    arg, msgbuf, bufsize);
1222
0
            }
1223
0
            if (*buffer == NULL) {
1224
0
                *buffer = PyMem_NEW(char, size + 1);
1225
0
                if (*buffer == NULL) {
1226
0
                    Py_DECREF(s);
1227
0
                    PyErr_NoMemory();
1228
0
                    RETURN_ERR_OCCURRED;
1229
0
                }
1230
0
                if (addcleanup(*buffer, freelist, cleanup_ptr)) {
1231
0
                    Py_DECREF(s);
1232
0
                    return converterr(
1233
0
                        "(cleanup problem)",
1234
0
                        arg, msgbuf, bufsize);
1235
0
                }
1236
0
            } else {
1237
0
                if (size + 1 > BUFFER_LEN) {
1238
0
                    Py_DECREF(s);
1239
0
                    PyErr_Format(PyExc_ValueError,
1240
0
                                 "encoded string too long "
1241
0
                                 "(%zd, maximum length %zd)",
1242
0
                                 (Py_ssize_t)size, (Py_ssize_t)(BUFFER_LEN-1));
1243
0
                    RETURN_ERR_OCCURRED;
1244
0
                }
1245
0
            }
1246
0
            memcpy(*buffer, ptr, size+1);
1247
1248
0
            if (flags & FLAG_SIZE_T) {
1249
0
                *q2 = size;
1250
0
            }
1251
0
            else {
1252
0
                if (INT_MAX < size) {
1253
0
                    Py_DECREF(s);
1254
0
                    PyErr_SetString(PyExc_OverflowError,
1255
0
                                    "size does not fit in an int");
1256
0
                    return converterr("", arg, msgbuf, bufsize);
1257
0
                }
1258
0
                *q = (int)size;
1259
0
            }
1260
0
        } else {
1261
            /* Using a 0-terminated buffer:
1262
1263
               - the encoded string has to be 0-terminated
1264
               for this variant to work; if it is not, an
1265
               error raised
1266
1267
               - a new buffer of the needed size is
1268
               allocated and the data copied into it;
1269
               *buffer is updated to point to the new
1270
               buffer; the caller is responsible for
1271
               PyMem_Free()ing it after usage
1272
1273
            */
1274
0
            if ((Py_ssize_t)strlen(ptr) != size) {
1275
0
                Py_DECREF(s);
1276
0
                return converterr(
1277
0
                    "encoded string without null bytes",
1278
0
                    arg, msgbuf, bufsize);
1279
0
            }
1280
0
            *buffer = PyMem_NEW(char, size + 1);
1281
0
            if (*buffer == NULL) {
1282
0
                Py_DECREF(s);
1283
0
                PyErr_NoMemory();
1284
0
                RETURN_ERR_OCCURRED;
1285
0
            }
1286
0
            if (addcleanup(*buffer, freelist, cleanup_ptr)) {
1287
0
                Py_DECREF(s);
1288
0
                return converterr("(cleanup problem)",
1289
0
                                arg, msgbuf, bufsize);
1290
0
            }
1291
0
            memcpy(*buffer, ptr, size+1);
1292
0
        }
1293
0
        Py_DECREF(s);
1294
0
        break;
1295
0
    }
1296
1297
0
    case 'S': { /* PyBytes object */
1298
0
        PyObject **p = va_arg(*p_va, PyObject **);
1299
0
        if (PyBytes_Check(arg))
1300
0
            *p = arg;
1301
0
        else
1302
0
            return converterr("bytes", arg, msgbuf, bufsize);
1303
0
        break;
1304
0
    }
1305
1306
0
    case 'Y': { /* PyByteArray object */
1307
0
        PyObject **p = va_arg(*p_va, PyObject **);
1308
0
        if (PyByteArray_Check(arg))
1309
0
            *p = arg;
1310
0
        else
1311
0
            return converterr("bytearray", arg, msgbuf, bufsize);
1312
0
        break;
1313
0
    }
1314
1315
3.14k
    case 'U': { /* PyUnicode object */
1316
3.14k
        PyObject **p = va_arg(*p_va, PyObject **);
1317
3.14k
        if (PyUnicode_Check(arg)) {
1318
3.14k
            if (PyUnicode_READY(arg) == -1)
1319
0
                RETURN_ERR_OCCURRED;
1320
3.14k
            *p = arg;
1321
3.14k
        }
1322
0
        else
1323
0
            return converterr("str", arg, msgbuf, bufsize);
1324
3.14k
        break;
1325
3.14k
    }
1326
1327
16.3k
    case 'O': { /* object */
1328
16.3k
        PyTypeObject *type;
1329
16.3k
        PyObject **p;
1330
16.3k
        if (*format == '!') {
1331
7.96k
            type = va_arg(*p_va, PyTypeObject*);
1332
7.96k
            p = va_arg(*p_va, PyObject **);
1333
7.96k
            format++;
1334
7.96k
            if (PyType_IsSubtype(arg->ob_type, type))
1335
7.96k
                *p = arg;
1336
0
            else
1337
0
                return converterr(type->tp_name, arg, msgbuf, bufsize);
1338
1339
7.96k
        }
1340
8.34k
        else if (*format == '&') {
1341
0
            typedef int (*converter)(PyObject *, void *);
1342
0
            converter convert = va_arg(*p_va, converter);
1343
0
            void *addr = va_arg(*p_va, void *);
1344
0
            int res;
1345
0
            format++;
1346
0
            if (! (res = (*convert)(arg, addr)))
1347
0
                return converterr("(unspecified)",
1348
0
                                  arg, msgbuf, bufsize);
1349
0
            if (res == Py_CLEANUP_SUPPORTED &&
1350
0
                addcleanup(addr, freelist, convert) == -1)
1351
0
                return converterr("(cleanup problem)",
1352
0
                                arg, msgbuf, bufsize);
1353
0
        }
1354
8.34k
        else {
1355
8.34k
            p = va_arg(*p_va, PyObject **);
1356
8.34k
            *p = arg;
1357
8.34k
        }
1358
16.3k
        break;
1359
16.3k
    }
1360
1361
1362
16.3k
    case 'w': { /* "w*": memory buffer, read-write access */
1363
0
        void **p = va_arg(*p_va, void **);
1364
1365
0
        if (*format != '*')
1366
0
            return converterr(
1367
0
                "(invalid use of 'w' format character)",
1368
0
                arg, msgbuf, bufsize);
1369
0
        format++;
1370
1371
        /* Caller is interested in Py_buffer, and the object
1372
           supports it directly. */
1373
0
        if (PyObject_GetBuffer(arg, (Py_buffer*)p, PyBUF_WRITABLE) < 0) {
1374
0
            PyErr_Clear();
1375
0
            return converterr("read-write bytes-like object",
1376
0
                              arg, msgbuf, bufsize);
1377
0
        }
1378
0
        if (!PyBuffer_IsContiguous((Py_buffer*)p, 'C')) {
1379
0
            PyBuffer_Release((Py_buffer*)p);
1380
0
            return converterr("contiguous buffer", arg, msgbuf, bufsize);
1381
0
        }
1382
0
        if (addcleanup(p, freelist, cleanup_buffer)) {
1383
0
            return converterr(
1384
0
                "(cleanup problem)",
1385
0
                arg, msgbuf, bufsize);
1386
0
        }
1387
0
        break;
1388
0
    }
1389
1390
0
    default:
1391
0
        return converterr("(impossible<bad format char>)", arg, msgbuf, bufsize);
1392
1393
23.9k
    }
1394
1395
23.9k
    *p_format = format;
1396
23.9k
    return NULL;
1397
1398
23.9k
#undef FETCH_SIZE
1399
23.9k
#undef STORE_SIZE
1400
23.9k
#undef BUFFER_LEN
1401
23.9k
#undef RETURN_ERR_OCCURRED
1402
23.9k
}
1403
1404
static Py_ssize_t
1405
convertbuffer(PyObject *arg, const void **p, const char **errmsg)
1406
2.42k
{
1407
2.42k
    PyBufferProcs *pb = Py_TYPE(arg)->tp_as_buffer;
1408
2.42k
    Py_ssize_t count;
1409
2.42k
    Py_buffer view;
1410
1411
2.42k
    *errmsg = NULL;
1412
2.42k
    *p = NULL;
1413
2.42k
    if (pb != NULL && pb->bf_releasebuffer != NULL) {
1414
0
        *errmsg = "read-only bytes-like object";
1415
0
        return -1;
1416
0
    }
1417
1418
2.42k
    if (getbuffer(arg, &view, errmsg) < 0)
1419
0
        return -1;
1420
2.42k
    count = view.len;
1421
2.42k
    *p = view.buf;
1422
2.42k
    PyBuffer_Release(&view);
1423
2.42k
    return count;
1424
2.42k
}
1425
1426
static int
1427
getbuffer(PyObject *arg, Py_buffer *view, const char **errmsg)
1428
2.42k
{
1429
2.42k
    if (PyObject_GetBuffer(arg, view, PyBUF_SIMPLE) != 0) {
1430
0
        *errmsg = "bytes-like object";
1431
0
        return -1;
1432
0
    }
1433
2.42k
    if (!PyBuffer_IsContiguous(view, 'C')) {
1434
0
        PyBuffer_Release(view);
1435
0
        *errmsg = "contiguous buffer";
1436
0
        return -1;
1437
0
    }
1438
2.42k
    return 0;
1439
2.42k
}
1440
1441
/* Support for keyword arguments donated by
1442
   Geoff Philbrick <philbric@delphi.hks.com> */
1443
1444
/* Return false (0) for error, else true. */
1445
int
1446
PyArg_ParseTupleAndKeywords(PyObject *args,
1447
                            PyObject *keywords,
1448
                            const char *format,
1449
                            char **kwlist, ...)
1450
1.91k
{
1451
1.91k
    int retval;
1452
1.91k
    va_list va;
1453
1454
1.91k
    if ((args == NULL || !PyTuple_Check(args)) ||
1455
1.91k
        (keywords != NULL && !PyDict_Check(keywords)) ||
1456
1.91k
        format == NULL ||
1457
1.91k
        kwlist == NULL)
1458
0
    {
1459
0
        PyErr_BadInternalCall();
1460
0
        return 0;
1461
0
    }
1462
1463
1.91k
    va_start(va, kwlist);
1464
1.91k
    retval = vgetargskeywords(args, keywords, format, kwlist, &va, 0);
1465
1.91k
    va_end(va);
1466
1.91k
    return retval;
1467
1.91k
}
1468
1469
int
1470
_PyArg_ParseTupleAndKeywords_SizeT(PyObject *args,
1471
                                  PyObject *keywords,
1472
                                  const char *format,
1473
                                  char **kwlist, ...)
1474
1.14k
{
1475
1.14k
    int retval;
1476
1.14k
    va_list va;
1477
1478
1.14k
    if ((args == NULL || !PyTuple_Check(args)) ||
1479
1.14k
        (keywords != NULL && !PyDict_Check(keywords)) ||
1480
1.14k
        format == NULL ||
1481
1.14k
        kwlist == NULL)
1482
0
    {
1483
0
        PyErr_BadInternalCall();
1484
0
        return 0;
1485
0
    }
1486
1487
1.14k
    va_start(va, kwlist);
1488
1.14k
    retval = vgetargskeywords(args, keywords, format,
1489
1.14k
                              kwlist, &va, FLAG_SIZE_T);
1490
1.14k
    va_end(va);
1491
1.14k
    return retval;
1492
1.14k
}
1493
1494
1495
int
1496
PyArg_VaParseTupleAndKeywords(PyObject *args,
1497
                              PyObject *keywords,
1498
                              const char *format,
1499
                              char **kwlist, va_list va)
1500
0
{
1501
0
    int retval;
1502
0
    va_list lva;
1503
1504
0
    if ((args == NULL || !PyTuple_Check(args)) ||
1505
0
        (keywords != NULL && !PyDict_Check(keywords)) ||
1506
0
        format == NULL ||
1507
0
        kwlist == NULL)
1508
0
    {
1509
0
        PyErr_BadInternalCall();
1510
0
        return 0;
1511
0
    }
1512
1513
0
    va_copy(lva, va);
1514
1515
0
    retval = vgetargskeywords(args, keywords, format, kwlist, &lva, 0);
1516
0
    va_end(lva);
1517
0
    return retval;
1518
0
}
1519
1520
int
1521
_PyArg_VaParseTupleAndKeywords_SizeT(PyObject *args,
1522
                                    PyObject *keywords,
1523
                                    const char *format,
1524
                                    char **kwlist, va_list va)
1525
0
{
1526
0
    int retval;
1527
0
    va_list lva;
1528
1529
0
    if ((args == NULL || !PyTuple_Check(args)) ||
1530
0
        (keywords != NULL && !PyDict_Check(keywords)) ||
1531
0
        format == NULL ||
1532
0
        kwlist == NULL)
1533
0
    {
1534
0
        PyErr_BadInternalCall();
1535
0
        return 0;
1536
0
    }
1537
1538
0
    va_copy(lva, va);
1539
1540
0
    retval = vgetargskeywords(args, keywords, format,
1541
0
                              kwlist, &lva, FLAG_SIZE_T);
1542
0
    va_end(lva);
1543
0
    return retval;
1544
0
}
1545
1546
int
1547
_PyArg_ParseTupleAndKeywordsFast(PyObject *args, PyObject *keywords,
1548
                            struct _PyArg_Parser *parser, ...)
1549
0
{
1550
0
    int retval;
1551
0
    va_list va;
1552
1553
0
    va_start(va, parser);
1554
0
    retval = vgetargskeywordsfast(args, keywords, parser, &va, 0);
1555
0
    va_end(va);
1556
0
    return retval;
1557
0
}
1558
1559
int
1560
_PyArg_ParseTupleAndKeywordsFast_SizeT(PyObject *args, PyObject *keywords,
1561
                            struct _PyArg_Parser *parser, ...)
1562
0
{
1563
0
    int retval;
1564
0
    va_list va;
1565
1566
0
    va_start(va, parser);
1567
0
    retval = vgetargskeywordsfast(args, keywords, parser, &va, FLAG_SIZE_T);
1568
0
    va_end(va);
1569
0
    return retval;
1570
0
}
1571
1572
int
1573
_PyArg_ParseStackAndKeywords(PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames,
1574
                  struct _PyArg_Parser *parser, ...)
1575
56
{
1576
56
    int retval;
1577
56
    va_list va;
1578
1579
56
    va_start(va, parser);
1580
56
    retval = vgetargskeywordsfast_impl(args, nargs, NULL, kwnames, parser, &va, 0);
1581
56
    va_end(va);
1582
56
    return retval;
1583
56
}
1584
1585
int
1586
_PyArg_ParseStackAndKeywords_SizeT(PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames,
1587
                        struct _PyArg_Parser *parser, ...)
1588
0
{
1589
0
    int retval;
1590
0
    va_list va;
1591
1592
0
    va_start(va, parser);
1593
0
    retval = vgetargskeywordsfast_impl(args, nargs, NULL, kwnames, parser, &va, FLAG_SIZE_T);
1594
0
    va_end(va);
1595
0
    return retval;
1596
0
}
1597
1598
1599
int
1600
_PyArg_VaParseTupleAndKeywordsFast(PyObject *args, PyObject *keywords,
1601
                            struct _PyArg_Parser *parser, va_list va)
1602
0
{
1603
0
    int retval;
1604
0
    va_list lva;
1605
1606
0
    va_copy(lva, va);
1607
1608
0
    retval = vgetargskeywordsfast(args, keywords, parser, &lva, 0);
1609
0
    va_end(lva);
1610
0
    return retval;
1611
0
}
1612
1613
int
1614
_PyArg_VaParseTupleAndKeywordsFast_SizeT(PyObject *args, PyObject *keywords,
1615
                            struct _PyArg_Parser *parser, va_list va)
1616
0
{
1617
0
    int retval;
1618
0
    va_list lva;
1619
1620
0
    va_copy(lva, va);
1621
1622
0
    retval = vgetargskeywordsfast(args, keywords, parser, &lva, FLAG_SIZE_T);
1623
0
    va_end(lva);
1624
0
    return retval;
1625
0
}
1626
1627
int
1628
PyArg_ValidateKeywordArguments(PyObject *kwargs)
1629
0
{
1630
0
    if (!PyDict_Check(kwargs)) {
1631
0
        PyErr_BadInternalCall();
1632
0
        return 0;
1633
0
    }
1634
0
    if (!_PyDict_HasOnlyStringKeys(kwargs)) {
1635
0
        PyErr_SetString(PyExc_TypeError,
1636
0
                        "keywords must be strings");
1637
0
        return 0;
1638
0
    }
1639
0
    return 1;
1640
0
}
1641
1642
8.46k
#define IS_END_OF_FORMAT(c) (c == '\0' || c == ';' || c == ':')
1643
1644
static int
1645
vgetargskeywords(PyObject *args, PyObject *kwargs, const char *format,
1646
                 char **kwlist, va_list *p_va, int flags)
1647
3.06k
{
1648
3.06k
    char msgbuf[512];
1649
3.06k
    int levels[32];
1650
3.06k
    const char *fname, *msg, *custom_msg;
1651
3.06k
    int min = INT_MAX;
1652
3.06k
    int max = INT_MAX;
1653
3.06k
    int i, pos, len;
1654
3.06k
    int skip = 0;
1655
3.06k
    Py_ssize_t nargs, nkwargs;
1656
3.06k
    PyObject *current_arg;
1657
3.06k
    freelistentry_t static_entries[STATIC_FREELIST_ENTRIES];
1658
3.06k
    freelist_t freelist;
1659
1660
3.06k
    freelist.entries = static_entries;
1661
3.06k
    freelist.first_available = 0;
1662
3.06k
    freelist.entries_malloced = 0;
1663
1664
3.06k
    assert(args != NULL && PyTuple_Check(args));
1665
3.06k
    assert(kwargs == NULL || PyDict_Check(kwargs));
1666
3.06k
    assert(format != NULL);
1667
3.06k
    assert(kwlist != NULL);
1668
3.06k
    assert(p_va != NULL);
1669
1670
    /* grab the function name or custom error msg first (mutually exclusive) */
1671
3.06k
    fname = strchr(format, ':');
1672
3.06k
    if (fname) {
1673
2.88k
        fname++;
1674
2.88k
        custom_msg = NULL;
1675
2.88k
    }
1676
178
    else {
1677
178
        custom_msg = strchr(format,';');
1678
178
        if (custom_msg)
1679
0
            custom_msg++;
1680
178
    }
1681
1682
    /* scan kwlist and count the number of positional-only parameters */
1683
3.06k
    for (pos = 0; kwlist[pos] && !*kwlist[pos]; pos++) {
1684
0
    }
1685
    /* scan kwlist and get greatest possible nbr of args */
1686
11.8k
    for (len = pos; kwlist[len]; len++) {
1687
8.80k
        if (!*kwlist[len]) {
1688
0
            PyErr_SetString(PyExc_SystemError,
1689
0
                            "Empty keyword parameter name");
1690
0
            return cleanreturn(0, &freelist);
1691
0
        }
1692
8.80k
    }
1693
1694
3.06k
    if (len > STATIC_FREELIST_ENTRIES) {
1695
0
        freelist.entries = PyMem_NEW(freelistentry_t, len);
1696
0
        if (freelist.entries == NULL) {
1697
0
            PyErr_NoMemory();
1698
0
            return 0;
1699
0
        }
1700
0
        freelist.entries_malloced = 1;
1701
0
    }
1702
1703
3.06k
    nargs = PyTuple_GET_SIZE(args);
1704
3.06k
    nkwargs = (kwargs == NULL) ? 0 : PyDict_GET_SIZE(kwargs);
1705
3.06k
    if (nargs + nkwargs > len) {
1706
        /* Adding "keyword" (when nargs == 0) prevents producing wrong error
1707
           messages in some special cases (see bpo-31229). */
1708
0
        PyErr_Format(PyExc_TypeError,
1709
0
                     "%.200s%s takes at most %d %sargument%s (%zd given)",
1710
0
                     (fname == NULL) ? "function" : fname,
1711
0
                     (fname == NULL) ? "" : "()",
1712
0
                     len,
1713
0
                     (nargs == 0) ? "keyword " : "",
1714
0
                     (len == 1) ? "" : "s",
1715
0
                     nargs + nkwargs);
1716
0
        return cleanreturn(0, &freelist);
1717
0
    }
1718
1719
    /* convert tuple args and keyword args in same loop, using kwlist to drive process */
1720
7.49k
    for (i = 0; i < len; i++) {
1721
6.52k
        if (*format == '|') {
1722
2.59k
            if (min != INT_MAX) {
1723
0
                PyErr_SetString(PyExc_SystemError,
1724
0
                                "Invalid format string (| specified twice)");
1725
0
                return cleanreturn(0, &freelist);
1726
0
            }
1727
1728
2.59k
            min = i;
1729
2.59k
            format++;
1730
1731
2.59k
            if (max != INT_MAX) {
1732
0
                PyErr_SetString(PyExc_SystemError,
1733
0
                                "Invalid format string ($ before |)");
1734
0
                return cleanreturn(0, &freelist);
1735
0
            }
1736
2.59k
        }
1737
6.52k
        if (*format == '$') {
1738
348
            if (max != INT_MAX) {
1739
0
                PyErr_SetString(PyExc_SystemError,
1740
0
                                "Invalid format string ($ specified twice)");
1741
0
                return cleanreturn(0, &freelist);
1742
0
            }
1743
1744
348
            max = i;
1745
348
            format++;
1746
1747
348
            if (max < pos) {
1748
0
                PyErr_SetString(PyExc_SystemError,
1749
0
                                "Empty parameter name after $");
1750
0
                return cleanreturn(0, &freelist);
1751
0
            }
1752
348
            if (skip) {
1753
                /* Now we know the minimal and the maximal numbers of
1754
                 * positional arguments and can raise an exception with
1755
                 * informative message (see below). */
1756
0
                break;
1757
0
            }
1758
348
            if (max < nargs) {
1759
0
                if (max == 0) {
1760
0
                    PyErr_Format(PyExc_TypeError,
1761
0
                                 "%.200s%s takes no positional arguments",
1762
0
                                 (fname == NULL) ? "function" : fname,
1763
0
                                 (fname == NULL) ? "" : "()");
1764
0
                }
1765
0
                else {
1766
0
                    PyErr_Format(PyExc_TypeError,
1767
0
                                 "%.200s%s takes %s %d positional argument%s"
1768
0
                                 " (%zd given)",
1769
0
                                 (fname == NULL) ? "function" : fname,
1770
0
                                 (fname == NULL) ? "" : "()",
1771
0
                                 (min != INT_MAX) ? "at most" : "exactly",
1772
0
                                 max,
1773
0
                                 max == 1 ? "" : "s",
1774
0
                                 nargs);
1775
0
                }
1776
0
                return cleanreturn(0, &freelist);
1777
0
            }
1778
348
        }
1779
6.52k
        if (IS_END_OF_FORMAT(*format)) {
1780
0
            PyErr_Format(PyExc_SystemError,
1781
0
                         "More keyword list entries (%d) than "
1782
0
                         "format specifiers (%d)", len, i);
1783
0
            return cleanreturn(0, &freelist);
1784
0
        }
1785
6.52k
        if (!skip) {
1786
6.52k
            if (i < nargs) {
1787
4.02k
                current_arg = PyTuple_GET_ITEM(args, i);
1788
4.02k
            }
1789
2.50k
            else if (nkwargs && i >= pos) {
1790
405
                current_arg = _PyDict_GetItemStringWithError(kwargs, kwlist[i]);
1791
405
                if (current_arg) {
1792
234
                    --nkwargs;
1793
234
                }
1794
171
                else if (PyErr_Occurred()) {
1795
0
                    return cleanreturn(0, &freelist);
1796
0
                }
1797
405
            }
1798
2.09k
            else {
1799
2.09k
                current_arg = NULL;
1800
2.09k
            }
1801
1802
6.52k
            if (current_arg) {
1803
4.25k
                msg = convertitem(current_arg, &format, p_va, flags,
1804
4.25k
                    levels, msgbuf, sizeof(msgbuf), &freelist);
1805
4.25k
                if (msg) {
1806
0
                    seterror(i+1, msg, levels, fname, custom_msg);
1807
0
                    return cleanreturn(0, &freelist);
1808
0
                }
1809
4.25k
                continue;
1810
4.25k
            }
1811
1812
2.26k
            if (i < min) {
1813
176
                if (i < pos) {
1814
0
                    assert (min == INT_MAX);
1815
0
                    assert (max == INT_MAX);
1816
0
                    skip = 1;
1817
                    /* At that moment we still don't know the minimal and
1818
                     * the maximal numbers of positional arguments.  Raising
1819
                     * an exception is deferred until we encounter | and $
1820
                     * or the end of the format. */
1821
0
                }
1822
176
                else {
1823
176
                    PyErr_Format(PyExc_TypeError,  "%.200s%s missing required "
1824
176
                                 "argument '%s' (pos %d)",
1825
176
                                 (fname == NULL) ? "function" : fname,
1826
176
                                 (fname == NULL) ? "" : "()",
1827
176
                                 kwlist[i], i+1);
1828
176
                    return cleanreturn(0, &freelist);
1829
176
                }
1830
176
            }
1831
            /* current code reports success when all required args
1832
             * fulfilled and no keyword args left, with no further
1833
             * validation. XXX Maybe skip this in debug build ?
1834
             */
1835
2.09k
            if (!nkwargs && !skip) {
1836
1.92k
                return cleanreturn(1, &freelist);
1837
1.92k
            }
1838
2.09k
        }
1839
1840
        /* We are into optional args, skip through to any remaining
1841
         * keyword args */
1842
171
        msg = skipitem(&format, p_va, flags);
1843
171
        if (msg) {
1844
0
            PyErr_Format(PyExc_SystemError, "%s: '%s'", msg,
1845
0
                         format);
1846
0
            return cleanreturn(0, &freelist);
1847
0
        }
1848
171
    }
1849
1850
968
    if (skip) {
1851
0
        PyErr_Format(PyExc_TypeError,
1852
0
                     "%.200s%s takes %s %d positional argument%s"
1853
0
                     " (%zd given)",
1854
0
                     (fname == NULL) ? "function" : fname,
1855
0
                     (fname == NULL) ? "" : "()",
1856
0
                     (Py_MIN(pos, min) < i) ? "at least" : "exactly",
1857
0
                     Py_MIN(pos, min),
1858
0
                     Py_MIN(pos, min) == 1 ? "" : "s",
1859
0
                     nargs);
1860
0
        return cleanreturn(0, &freelist);
1861
0
    }
1862
1863
968
    if (!IS_END_OF_FORMAT(*format) && (*format != '|') && (*format != '$')) {
1864
0
        PyErr_Format(PyExc_SystemError,
1865
0
            "more argument specifiers than keyword list entries "
1866
0
            "(remaining format:'%s')", format);
1867
0
        return cleanreturn(0, &freelist);
1868
0
    }
1869
1870
968
    if (nkwargs > 0) {
1871
0
        PyObject *key;
1872
0
        Py_ssize_t j;
1873
        /* make sure there are no arguments given by name and position */
1874
0
        for (i = pos; i < nargs; i++) {
1875
0
            current_arg = _PyDict_GetItemStringWithError(kwargs, kwlist[i]);
1876
0
            if (current_arg) {
1877
                /* arg present in tuple and in dict */
1878
0
                PyErr_Format(PyExc_TypeError,
1879
0
                             "argument for %.200s%s given by name ('%s') "
1880
0
                             "and position (%d)",
1881
0
                             (fname == NULL) ? "function" : fname,
1882
0
                             (fname == NULL) ? "" : "()",
1883
0
                             kwlist[i], i+1);
1884
0
                return cleanreturn(0, &freelist);
1885
0
            }
1886
0
            else if (PyErr_Occurred()) {
1887
0
                return cleanreturn(0, &freelist);
1888
0
            }
1889
0
        }
1890
        /* make sure there are no extraneous keyword arguments */
1891
0
        j = 0;
1892
0
        while (PyDict_Next(kwargs, &j, &key, NULL)) {
1893
0
            int match = 0;
1894
0
            if (!PyUnicode_Check(key)) {
1895
0
                PyErr_SetString(PyExc_TypeError,
1896
0
                                "keywords must be strings");
1897
0
                return cleanreturn(0, &freelist);
1898
0
            }
1899
0
            for (i = pos; i < len; i++) {
1900
0
                if (_PyUnicode_EqualToASCIIString(key, kwlist[i])) {
1901
0
                    match = 1;
1902
0
                    break;
1903
0
                }
1904
0
            }
1905
0
            if (!match) {
1906
0
                PyErr_Format(PyExc_TypeError,
1907
0
                             "'%U' is an invalid keyword "
1908
0
                             "argument for %.200s%s",
1909
0
                             key,
1910
0
                             (fname == NULL) ? "this function" : fname,
1911
0
                             (fname == NULL) ? "" : "()");
1912
0
                return cleanreturn(0, &freelist);
1913
0
            }
1914
0
        }
1915
0
    }
1916
1917
968
    return cleanreturn(1, &freelist);
1918
968
}
1919
1920
1921
/* List of static parsers. */
1922
static struct _PyArg_Parser *static_arg_parsers = NULL;
1923
1924
static int
1925
parser_init(struct _PyArg_Parser *parser)
1926
62
{
1927
62
    const char * const *keywords;
1928
62
    const char *format, *msg;
1929
62
    int i, len, min, max, nkw;
1930
62
    PyObject *kwtuple;
1931
1932
62
    assert(parser->keywords != NULL);
1933
62
    if (parser->kwtuple != NULL) {
1934
58
        return 1;
1935
58
    }
1936
1937
4
    keywords = parser->keywords;
1938
    /* scan keywords and count the number of positional-only parameters */
1939
4
    for (i = 0; keywords[i] && !*keywords[i]; i++) {
1940
0
    }
1941
4
    parser->pos = i;
1942
    /* scan keywords and get greatest possible nbr of args */
1943
19
    for (; keywords[i]; i++) {
1944
15
        if (!*keywords[i]) {
1945
0
            PyErr_SetString(PyExc_SystemError,
1946
0
                            "Empty keyword parameter name");
1947
0
            return 0;
1948
0
        }
1949
15
    }
1950
4
    len = i;
1951
1952
4
    format = parser->format;
1953
4
    if (format) {
1954
        /* grab the function name or custom error msg first (mutually exclusive) */
1955
1
        parser->fname = strchr(parser->format, ':');
1956
1
        if (parser->fname) {
1957
1
            parser->fname++;
1958
1
            parser->custom_msg = NULL;
1959
1
        }
1960
0
        else {
1961
0
            parser->custom_msg = strchr(parser->format,';');
1962
0
            if (parser->custom_msg)
1963
0
                parser->custom_msg++;
1964
0
        }
1965
1966
1
        min = max = INT_MAX;
1967
5
        for (i = 0; i < len; i++) {
1968
4
            if (*format == '|') {
1969
1
                if (min != INT_MAX) {
1970
0
                    PyErr_SetString(PyExc_SystemError,
1971
0
                                    "Invalid format string (| specified twice)");
1972
0
                    return 0;
1973
0
                }
1974
1
                if (max != INT_MAX) {
1975
0
                    PyErr_SetString(PyExc_SystemError,
1976
0
                                    "Invalid format string ($ before |)");
1977
0
                    return 0;
1978
0
                }
1979
1
                min = i;
1980
1
                format++;
1981
1
            }
1982
4
            if (*format == '$') {
1983
0
                if (max != INT_MAX) {
1984
0
                    PyErr_SetString(PyExc_SystemError,
1985
0
                                    "Invalid format string ($ specified twice)");
1986
0
                    return 0;
1987
0
                }
1988
0
                if (i < parser->pos) {
1989
0
                    PyErr_SetString(PyExc_SystemError,
1990
0
                                    "Empty parameter name after $");
1991
0
                    return 0;
1992
0
                }
1993
0
                max = i;
1994
0
                format++;
1995
0
            }
1996
4
            if (IS_END_OF_FORMAT(*format)) {
1997
0
                PyErr_Format(PyExc_SystemError,
1998
0
                            "More keyword list entries (%d) than "
1999
0
                            "format specifiers (%d)", len, i);
2000
0
                return 0;
2001
0
            }
2002
2003
4
            msg = skipitem(&format, NULL, 0);
2004
4
            if (msg) {
2005
0
                PyErr_Format(PyExc_SystemError, "%s: '%s'", msg,
2006
0
                            format);
2007
0
                return 0;
2008
0
            }
2009
4
        }
2010
1
        parser->min = Py_MIN(min, len);
2011
1
        parser->max = Py_MIN(max, len);
2012
2013
1
        if (!IS_END_OF_FORMAT(*format) && (*format != '|') && (*format != '$')) {
2014
0
            PyErr_Format(PyExc_SystemError,
2015
0
                "more argument specifiers than keyword list entries "
2016
0
                "(remaining format:'%s')", format);
2017
0
            return 0;
2018
0
        }
2019
1
    }
2020
2021
4
    nkw = len - parser->pos;
2022
4
    kwtuple = PyTuple_New(nkw);
2023
4
    if (kwtuple == NULL) {
2024
0
        return 0;
2025
0
    }
2026
4
    keywords = parser->keywords + parser->pos;
2027
19
    for (i = 0; i < nkw; i++) {
2028
15
        PyObject *str = PyUnicode_FromString(keywords[i]);
2029
15
        if (str == NULL) {
2030
0
            Py_DECREF(kwtuple);
2031
0
            return 0;
2032
0
        }
2033
15
        PyUnicode_InternInPlace(&str);
2034
15
        PyTuple_SET_ITEM(kwtuple, i, str);
2035
15
    }
2036
4
    parser->kwtuple = kwtuple;
2037
2038
4
    assert(parser->next == NULL);
2039
4
    parser->next = static_arg_parsers;
2040
4
    static_arg_parsers = parser;
2041
4
    return 1;
2042
4
}
2043
2044
static void
2045
parser_clear(struct _PyArg_Parser *parser)
2046
0
{
2047
0
    Py_CLEAR(parser->kwtuple);
2048
0
}
2049
2050
static PyObject*
2051
find_keyword(PyObject *kwnames, PyObject *const *kwstack, PyObject *key)
2052
179
{
2053
179
    Py_ssize_t i, nkwargs;
2054
2055
179
    nkwargs = PyTuple_GET_SIZE(kwnames);
2056
354
    for (i=0; i < nkwargs; i++) {
2057
296
        PyObject *kwname = PyTuple_GET_ITEM(kwnames, i);
2058
2059
        /* ptr==ptr should match in most cases since keyword keys
2060
           should be interned strings */
2061
296
        if (kwname == key) {
2062
121
            return kwstack[i];
2063
121
        }
2064
175
        if (!PyUnicode_Check(kwname)) {
2065
            /* ignore non-string keyword keys:
2066
               an error will be raised below */
2067
0
            continue;
2068
0
        }
2069
175
        if (_PyUnicode_EQ(kwname, key)) {
2070
0
            return kwstack[i];
2071
0
        }
2072
175
    }
2073
58
    return NULL;
2074
179
}
2075
2076
static int
2077
vgetargskeywordsfast_impl(PyObject *const *args, Py_ssize_t nargs,
2078
                          PyObject *kwargs, PyObject *kwnames,
2079
                          struct _PyArg_Parser *parser,
2080
                          va_list *p_va, int flags)
2081
56
{
2082
56
    PyObject *kwtuple;
2083
56
    char msgbuf[512];
2084
56
    int levels[32];
2085
56
    const char *format;
2086
56
    const char *msg;
2087
56
    PyObject *keyword;
2088
56
    int i, pos, len;
2089
56
    Py_ssize_t nkwargs;
2090
56
    PyObject *current_arg;
2091
56
    freelistentry_t static_entries[STATIC_FREELIST_ENTRIES];
2092
56
    freelist_t freelist;
2093
56
    PyObject *const *kwstack = NULL;
2094
2095
56
    freelist.entries = static_entries;
2096
56
    freelist.first_available = 0;
2097
56
    freelist.entries_malloced = 0;
2098
2099
56
    assert(kwargs == NULL || PyDict_Check(kwargs));
2100
56
    assert(kwargs == NULL || kwnames == NULL);
2101
56
    assert(p_va != NULL);
2102
2103
56
    if (parser == NULL) {
2104
0
        PyErr_BadInternalCall();
2105
0
        return 0;
2106
0
    }
2107
2108
56
    if (kwnames != NULL && !PyTuple_Check(kwnames)) {
2109
0
        PyErr_BadInternalCall();
2110
0
        return 0;
2111
0
    }
2112
2113
56
    if (!parser_init(parser)) {
2114
0
        return 0;
2115
0
    }
2116
2117
56
    kwtuple = parser->kwtuple;
2118
56
    pos = parser->pos;
2119
56
    len = pos + (int)PyTuple_GET_SIZE(kwtuple);
2120
2121
56
    if (len > STATIC_FREELIST_ENTRIES) {
2122
0
        freelist.entries = PyMem_NEW(freelistentry_t, len);
2123
0
        if (freelist.entries == NULL) {
2124
0
            PyErr_NoMemory();
2125
0
            return 0;
2126
0
        }
2127
0
        freelist.entries_malloced = 1;
2128
0
    }
2129
2130
56
    if (kwargs != NULL) {
2131
0
        nkwargs = PyDict_GET_SIZE(kwargs);
2132
0
    }
2133
56
    else if (kwnames != NULL) {
2134
56
        nkwargs = PyTuple_GET_SIZE(kwnames);
2135
56
        kwstack = args + nargs;
2136
56
    }
2137
0
    else {
2138
0
        nkwargs = 0;
2139
0
    }
2140
56
    if (nargs + nkwargs > len) {
2141
        /* Adding "keyword" (when nargs == 0) prevents producing wrong error
2142
           messages in some special cases (see bpo-31229). */
2143
0
        PyErr_Format(PyExc_TypeError,
2144
0
                     "%.200s%s takes at most %d %sargument%s (%zd given)",
2145
0
                     (parser->fname == NULL) ? "function" : parser->fname,
2146
0
                     (parser->fname == NULL) ? "" : "()",
2147
0
                     len,
2148
0
                     (nargs == 0) ? "keyword " : "",
2149
0
                     (len == 1) ? "" : "s",
2150
0
                     nargs + nkwargs);
2151
0
        return cleanreturn(0, &freelist);
2152
0
    }
2153
56
    if (parser->max < nargs) {
2154
0
        if (parser->max == 0) {
2155
0
            PyErr_Format(PyExc_TypeError,
2156
0
                         "%.200s%s takes no positional arguments",
2157
0
                         (parser->fname == NULL) ? "function" : parser->fname,
2158
0
                         (parser->fname == NULL) ? "" : "()");
2159
0
        }
2160
0
        else {
2161
0
            PyErr_Format(PyExc_TypeError,
2162
0
                         "%.200s%s takes %s %d positional argument%s (%zd given)",
2163
0
                         (parser->fname == NULL) ? "function" : parser->fname,
2164
0
                         (parser->fname == NULL) ? "" : "()",
2165
0
                         (parser->min < parser->max) ? "at most" : "exactly",
2166
0
                         parser->max,
2167
0
                         parser->max == 1 ? "" : "s",
2168
0
                         nargs);
2169
0
        }
2170
0
        return cleanreturn(0, &freelist);
2171
0
    }
2172
2173
56
    format = parser->format;
2174
    /* convert tuple args and keyword args in same loop, using kwtuple to drive process */
2175
224
    for (i = 0; i < len; i++) {
2176
224
        if (*format == '|') {
2177
56
            format++;
2178
56
        }
2179
224
        if (*format == '$') {
2180
0
            format++;
2181
0
        }
2182
224
        assert(!IS_END_OF_FORMAT(*format));
2183
2184
224
        if (i < nargs) {
2185
0
            current_arg = args[i];
2186
0
        }
2187
224
        else if (nkwargs && i >= pos) {
2188
168
            keyword = PyTuple_GET_ITEM(kwtuple, i - pos);
2189
168
            if (kwargs != NULL) {
2190
0
                current_arg = PyDict_GetItemWithError(kwargs, keyword);
2191
0
                if (!current_arg && PyErr_Occurred()) {
2192
0
                    return cleanreturn(0, &freelist);
2193
0
                }
2194
0
            }
2195
168
            else {
2196
168
                current_arg = find_keyword(kwnames, kwstack, keyword);
2197
168
            }
2198
168
            if (current_arg) {
2199
112
                --nkwargs;
2200
112
            }
2201
168
        }
2202
56
        else {
2203
56
            current_arg = NULL;
2204
56
        }
2205
2206
224
        if (current_arg) {
2207
112
            msg = convertitem(current_arg, &format, p_va, flags,
2208
112
                levels, msgbuf, sizeof(msgbuf), &freelist);
2209
112
            if (msg) {
2210
0
                seterror(i+1, msg, levels, parser->fname, parser->custom_msg);
2211
0
                return cleanreturn(0, &freelist);
2212
0
            }
2213
112
            continue;
2214
112
        }
2215
2216
112
        if (i < parser->min) {
2217
            /* Less arguments than required */
2218
0
            if (i < pos) {
2219
0
                Py_ssize_t min = Py_MIN(pos, parser->min);
2220
0
                PyErr_Format(PyExc_TypeError,
2221
0
                             "%.200s%s takes %s %d positional argument%s"
2222
0
                             " (%zd given)",
2223
0
                             (parser->fname == NULL) ? "function" : parser->fname,
2224
0
                             (parser->fname == NULL) ? "" : "()",
2225
0
                             min < parser->max ? "at least" : "exactly",
2226
0
                             min,
2227
0
                             min == 1 ? "" : "s",
2228
0
                             nargs);
2229
0
            }
2230
0
            else {
2231
0
                keyword = PyTuple_GET_ITEM(kwtuple, i - pos);
2232
0
                PyErr_Format(PyExc_TypeError,  "%.200s%s missing required "
2233
0
                             "argument '%U' (pos %d)",
2234
0
                             (parser->fname == NULL) ? "function" : parser->fname,
2235
0
                             (parser->fname == NULL) ? "" : "()",
2236
0
                             keyword, i+1);
2237
0
            }
2238
0
            return cleanreturn(0, &freelist);
2239
0
        }
2240
        /* current code reports success when all required args
2241
         * fulfilled and no keyword args left, with no further
2242
         * validation. XXX Maybe skip this in debug build ?
2243
         */
2244
112
        if (!nkwargs) {
2245
56
            return cleanreturn(1, &freelist);
2246
56
        }
2247
2248
        /* We are into optional args, skip through to any remaining
2249
         * keyword args */
2250
56
        msg = skipitem(&format, p_va, flags);
2251
56
        assert(msg == NULL);
2252
56
    }
2253
2254
0
    assert(IS_END_OF_FORMAT(*format) || (*format == '|') || (*format == '$'));
2255
2256
0
    if (nkwargs > 0) {
2257
0
        Py_ssize_t j;
2258
        /* make sure there are no arguments given by name and position */
2259
0
        for (i = pos; i < nargs; i++) {
2260
0
            keyword = PyTuple_GET_ITEM(kwtuple, i - pos);
2261
0
            if (kwargs != NULL) {
2262
0
                current_arg = PyDict_GetItemWithError(kwargs, keyword);
2263
0
                if (!current_arg && PyErr_Occurred()) {
2264
0
                    return cleanreturn(0, &freelist);
2265
0
                }
2266
0
            }
2267
0
            else {
2268
0
                current_arg = find_keyword(kwnames, kwstack, keyword);
2269
0
            }
2270
0
            if (current_arg) {
2271
                /* arg present in tuple and in dict */
2272
0
                PyErr_Format(PyExc_TypeError,
2273
0
                             "argument for %.200s%s given by name ('%U') "
2274
0
                             "and position (%d)",
2275
0
                             (parser->fname == NULL) ? "function" : parser->fname,
2276
0
                             (parser->fname == NULL) ? "" : "()",
2277
0
                             keyword, i+1);
2278
0
                return cleanreturn(0, &freelist);
2279
0
            }
2280
0
        }
2281
        /* make sure there are no extraneous keyword arguments */
2282
0
        j = 0;
2283
0
        while (1) {
2284
0
            int match;
2285
0
            if (kwargs != NULL) {
2286
0
                if (!PyDict_Next(kwargs, &j, &keyword, NULL))
2287
0
                    break;
2288
0
            }
2289
0
            else {
2290
0
                if (j >= PyTuple_GET_SIZE(kwnames))
2291
0
                    break;
2292
0
                keyword = PyTuple_GET_ITEM(kwnames, j);
2293
0
                j++;
2294
0
            }
2295
2296
0
            if (!PyUnicode_Check(keyword)) {
2297
0
                PyErr_SetString(PyExc_TypeError,
2298
0
                                "keywords must be strings");
2299
0
                return cleanreturn(0, &freelist);
2300
0
            }
2301
0
            match = PySequence_Contains(kwtuple, keyword);
2302
0
            if (match <= 0) {
2303
0
                if (!match) {
2304
0
                    PyErr_Format(PyExc_TypeError,
2305
0
                                 "'%U' is an invalid keyword "
2306
0
                                 "argument for %.200s%s",
2307
0
                                 keyword,
2308
0
                                 (parser->fname == NULL) ? "this function" : parser->fname,
2309
0
                                 (parser->fname == NULL) ? "" : "()");
2310
0
                }
2311
0
                return cleanreturn(0, &freelist);
2312
0
            }
2313
0
        }
2314
0
    }
2315
2316
0
    return cleanreturn(1, &freelist);
2317
0
}
2318
2319
static int
2320
vgetargskeywordsfast(PyObject *args, PyObject *keywords,
2321
                     struct _PyArg_Parser *parser, va_list *p_va, int flags)
2322
0
{
2323
0
    PyObject **stack;
2324
0
    Py_ssize_t nargs;
2325
2326
0
    if (args == NULL
2327
0
        || !PyTuple_Check(args)
2328
0
        || (keywords != NULL && !PyDict_Check(keywords)))
2329
0
    {
2330
0
        PyErr_BadInternalCall();
2331
0
        return 0;
2332
0
    }
2333
2334
0
    stack = _PyTuple_ITEMS(args);
2335
0
    nargs = PyTuple_GET_SIZE(args);
2336
0
    return vgetargskeywordsfast_impl(stack, nargs, keywords, NULL,
2337
0
                                     parser, p_va, flags);
2338
0
}
2339
2340
2341
#undef _PyArg_UnpackKeywords
2342
2343
PyObject * const *
2344
_PyArg_UnpackKeywords(PyObject *const *args, Py_ssize_t nargs,
2345
                      PyObject *kwargs, PyObject *kwnames,
2346
                      struct _PyArg_Parser *parser,
2347
                      int minpos, int maxpos, int minkw,
2348
                      PyObject **buf)
2349
6
{
2350
6
    PyObject *kwtuple;
2351
6
    PyObject *keyword;
2352
6
    int i, posonly, minposonly, maxargs;
2353
6
    int reqlimit = minkw ? maxpos + minkw : minpos;
2354
6
    Py_ssize_t nkwargs;
2355
6
    PyObject *current_arg;
2356
6
    PyObject * const *kwstack = NULL;
2357
2358
6
    assert(kwargs == NULL || PyDict_Check(kwargs));
2359
6
    assert(kwargs == NULL || kwnames == NULL);
2360
2361
6
    if (parser == NULL) {
2362
0
        PyErr_BadInternalCall();
2363
0
        return NULL;
2364
0
    }
2365
2366
6
    if (kwnames != NULL && !PyTuple_Check(kwnames)) {
2367
0
        PyErr_BadInternalCall();
2368
0
        return NULL;
2369
0
    }
2370
2371
6
    if (args == NULL && nargs == 0) {
2372
0
        args = buf;
2373
0
    }
2374
2375
6
    if (!parser_init(parser)) {
2376
0
        return NULL;
2377
0
    }
2378
2379
6
    kwtuple = parser->kwtuple;
2380
6
    posonly = parser->pos;
2381
6
    minposonly = Py_MIN(posonly, minpos);
2382
6
    maxargs = posonly + (int)PyTuple_GET_SIZE(kwtuple);
2383
2384
6
    if (kwargs != NULL) {
2385
1
        nkwargs = PyDict_GET_SIZE(kwargs);
2386
1
    }
2387
5
    else if (kwnames != NULL) {
2388
5
        nkwargs = PyTuple_GET_SIZE(kwnames);
2389
5
        kwstack = args + nargs;
2390
5
    }
2391
0
    else {
2392
0
        nkwargs = 0;
2393
0
    }
2394
6
    if (nkwargs == 0 && minkw == 0 && minpos <= nargs && nargs <= maxpos) {
2395
        /* Fast path. */
2396
0
        return args;
2397
0
    }
2398
6
    if (nargs + nkwargs > maxargs) {
2399
        /* Adding "keyword" (when nargs == 0) prevents producing wrong error
2400
           messages in some special cases (see bpo-31229). */
2401
0
        PyErr_Format(PyExc_TypeError,
2402
0
                     "%.200s%s takes at most %d %sargument%s (%zd given)",
2403
0
                     (parser->fname == NULL) ? "function" : parser->fname,
2404
0
                     (parser->fname == NULL) ? "" : "()",
2405
0
                     maxargs,
2406
0
                     (nargs == 0) ? "keyword " : "",
2407
0
                     (maxargs == 1) ? "" : "s",
2408
0
                     nargs + nkwargs);
2409
0
        return NULL;
2410
0
    }
2411
6
    if (nargs > maxpos) {
2412
0
        if (maxpos == 0) {
2413
0
            PyErr_Format(PyExc_TypeError,
2414
0
                         "%.200s%s takes no positional arguments",
2415
0
                         (parser->fname == NULL) ? "function" : parser->fname,
2416
0
                         (parser->fname == NULL) ? "" : "()");
2417
0
        }
2418
0
        else {
2419
0
            PyErr_Format(PyExc_TypeError,
2420
0
                         "%.200s%s takes %s %d positional argument%s (%zd given)",
2421
0
                         (parser->fname == NULL) ? "function" : parser->fname,
2422
0
                         (parser->fname == NULL) ? "" : "()",
2423
0
                         (minpos < maxpos) ? "at most" : "exactly",
2424
0
                         maxpos,
2425
0
                         (maxpos == 1) ? "" : "s",
2426
0
                         nargs);
2427
0
        }
2428
0
        return NULL;
2429
0
    }
2430
6
    if (nargs < minposonly) {
2431
0
        PyErr_Format(PyExc_TypeError,
2432
0
                     "%.200s%s takes %s %d positional argument%s"
2433
0
                     " (%zd given)",
2434
0
                     (parser->fname == NULL) ? "function" : parser->fname,
2435
0
                     (parser->fname == NULL) ? "" : "()",
2436
0
                     minposonly < maxpos ? "at least" : "exactly",
2437
0
                     minposonly,
2438
0
                     minposonly == 1 ? "" : "s",
2439
0
                     nargs);
2440
0
        return NULL;
2441
0
    }
2442
2443
    /* copy tuple args */
2444
8
    for (i = 0; i < nargs; i++) {
2445
2
        buf[i] = args[i];
2446
2
    }
2447
2448
    /* copy keyword args using kwtuple to drive process */
2449
20
    for (i = Py_MAX((int)nargs, posonly); i < maxargs; i++) {
2450
16
        if (nkwargs) {
2451
14
            keyword = PyTuple_GET_ITEM(kwtuple, i - posonly);
2452
14
            if (kwargs != NULL) {
2453
3
                current_arg = PyDict_GetItemWithError(kwargs, keyword);
2454
3
                if (!current_arg && PyErr_Occurred()) {
2455
0
                    return NULL;
2456
0
                }
2457
3
            }
2458
11
            else {
2459
11
                current_arg = find_keyword(kwnames, kwstack, keyword);
2460
11
            }
2461
14
        }
2462
2
        else if (i >= reqlimit) {
2463
2
            break;
2464
2
        }
2465
0
        else {
2466
0
            current_arg = NULL;
2467
0
        }
2468
2469
14
        buf[i] = current_arg;
2470
2471
14
        if (current_arg) {
2472
10
            --nkwargs;
2473
10
        }
2474
4
        else if (i < minpos || (maxpos <= i && i < reqlimit)) {
2475
            /* Less arguments than required */
2476
0
            keyword = PyTuple_GET_ITEM(kwtuple, i - posonly);
2477
0
            PyErr_Format(PyExc_TypeError,  "%.200s%s missing required "
2478
0
                         "argument '%U' (pos %d)",
2479
0
                         (parser->fname == NULL) ? "function" : parser->fname,
2480
0
                         (parser->fname == NULL) ? "" : "()",
2481
0
                         keyword, i+1);
2482
0
            return NULL;
2483
0
        }
2484
14
    }
2485
2486
6
    if (nkwargs > 0) {
2487
0
        Py_ssize_t j;
2488
        /* make sure there are no arguments given by name and position */
2489
0
        for (i = posonly; i < nargs; i++) {
2490
0
            keyword = PyTuple_GET_ITEM(kwtuple, i - posonly);
2491
0
            if (kwargs != NULL) {
2492
0
                current_arg = PyDict_GetItemWithError(kwargs, keyword);
2493
0
                if (!current_arg && PyErr_Occurred()) {
2494
0
                    return NULL;
2495
0
                }
2496
0
            }
2497
0
            else {
2498
0
                current_arg = find_keyword(kwnames, kwstack, keyword);
2499
0
            }
2500
0
            if (current_arg) {
2501
                /* arg present in tuple and in dict */
2502
0
                PyErr_Format(PyExc_TypeError,
2503
0
                             "argument for %.200s%s given by name ('%U') "
2504
0
                             "and position (%d)",
2505
0
                             (parser->fname == NULL) ? "function" : parser->fname,
2506
0
                             (parser->fname == NULL) ? "" : "()",
2507
0
                             keyword, i+1);
2508
0
                return NULL;
2509
0
            }
2510
0
        }
2511
        /* make sure there are no extraneous keyword arguments */
2512
0
        j = 0;
2513
0
        while (1) {
2514
0
            int match;
2515
0
            if (kwargs != NULL) {
2516
0
                if (!PyDict_Next(kwargs, &j, &keyword, NULL))
2517
0
                    break;
2518
0
            }
2519
0
            else {
2520
0
                if (j >= PyTuple_GET_SIZE(kwnames))
2521
0
                    break;
2522
0
                keyword = PyTuple_GET_ITEM(kwnames, j);
2523
0
                j++;
2524
0
            }
2525
2526
0
            if (!PyUnicode_Check(keyword)) {
2527
0
                PyErr_SetString(PyExc_TypeError,
2528
0
                                "keywords must be strings");
2529
0
                return NULL;
2530
0
            }
2531
0
            match = PySequence_Contains(kwtuple, keyword);
2532
0
            if (match <= 0) {
2533
0
                if (!match) {
2534
0
                    PyErr_Format(PyExc_TypeError,
2535
0
                                 "'%U' is an invalid keyword "
2536
0
                                 "argument for %.200s%s",
2537
0
                                 keyword,
2538
0
                                 (parser->fname == NULL) ? "this function" : parser->fname,
2539
0
                                 (parser->fname == NULL) ? "" : "()");
2540
0
                }
2541
0
                return NULL;
2542
0
            }
2543
0
        }
2544
0
    }
2545
2546
6
    return buf;
2547
6
}
2548
2549
2550
static const char *
2551
skipitem(const char **p_format, va_list *p_va, int flags)
2552
231
{
2553
231
    const char *format = *p_format;
2554
231
    char c = *format++;
2555
2556
231
    switch (c) {
2557
2558
    /*
2559
     * codes that take a single data pointer as an argument
2560
     * (the type of the pointer is irrelevant)
2561
     */
2562
2563
0
    case 'b': /* byte -- very short int */
2564
0
    case 'B': /* byte as bitfield */
2565
0
    case 'h': /* short int */
2566
0
    case 'H': /* short int as bitfield */
2567
0
    case 'i': /* int */
2568
0
    case 'I': /* int sized bitfield */
2569
0
    case 'l': /* long int */
2570
0
    case 'k': /* long int sized bitfield */
2571
0
    case 'L': /* long long */
2572
0
    case 'K': /* long long sized bitfield */
2573
0
    case 'n': /* Py_ssize_t */
2574
0
    case 'f': /* float */
2575
0
    case 'd': /* double */
2576
0
    case 'D': /* complex double */
2577
0
    case 'c': /* char */
2578
0
    case 'C': /* unicode char */
2579
0
    case 'p': /* boolean predicate */
2580
0
    case 'S': /* string object */
2581
0
    case 'Y': /* string object */
2582
0
    case 'U': /* unicode string object */
2583
0
        {
2584
0
            if (p_va != NULL) {
2585
0
                (void) va_arg(*p_va, void *);
2586
0
            }
2587
0
            break;
2588
0
        }
2589
2590
    /* string codes */
2591
2592
0
    case 'e': /* string with encoding */
2593
0
        {
2594
0
            if (p_va != NULL) {
2595
0
                (void) va_arg(*p_va, const char *);
2596
0
            }
2597
0
            if (!(*format == 's' || *format == 't'))
2598
                /* after 'e', only 's' and 't' is allowed */
2599
0
                goto err;
2600
0
            format++;
2601
0
        }
2602
        /* fall through */
2603
2604
0
    case 's': /* string */
2605
0
    case 'z': /* string or None */
2606
0
    case 'y': /* bytes */
2607
0
    case 'u': /* unicode string */
2608
0
    case 'Z': /* unicode string or None */
2609
0
    case 'w': /* buffer, read-write */
2610
0
        {
2611
0
            if (p_va != NULL) {
2612
0
                (void) va_arg(*p_va, char **);
2613
0
            }
2614
0
            if (*format == '#') {
2615
0
                if (p_va != NULL) {
2616
0
                    if (flags & FLAG_SIZE_T)
2617
0
                        (void) va_arg(*p_va, Py_ssize_t *);
2618
0
                    else {
2619
0
                        if (PyErr_WarnEx(PyExc_DeprecationWarning,
2620
0
                                    "PY_SSIZE_T_CLEAN will be required for '#' formats", 1)) {
2621
0
                            return NULL;
2622
0
                        }
2623
0
                        (void) va_arg(*p_va, int *);
2624
0
                    }
2625
0
                }
2626
0
                format++;
2627
0
            } else if ((c == 's' || c == 'z' || c == 'y' || c == 'w')
2628
0
                       && *format == '*')
2629
0
            {
2630
0
                format++;
2631
0
            }
2632
0
            break;
2633
0
        }
2634
2635
231
    case 'O': /* object */
2636
231
        {
2637
231
            if (*format == '!') {
2638
0
                format++;
2639
0
                if (p_va != NULL) {
2640
0
                    (void) va_arg(*p_va, PyTypeObject*);
2641
0
                    (void) va_arg(*p_va, PyObject **);
2642
0
                }
2643
0
            }
2644
231
            else if (*format == '&') {
2645
0
                typedef int (*converter)(PyObject *, void *);
2646
0
                if (p_va != NULL) {
2647
0
                    (void) va_arg(*p_va, converter);
2648
0
                    (void) va_arg(*p_va, void *);
2649
0
                }
2650
0
                format++;
2651
0
            }
2652
231
            else {
2653
231
                if (p_va != NULL) {
2654
227
                    (void) va_arg(*p_va, PyObject **);
2655
227
                }
2656
231
            }
2657
231
            break;
2658
0
        }
2659
2660
0
    case '(':           /* bypass tuple, not handled at all previously */
2661
0
        {
2662
0
            const char *msg;
2663
0
            for (;;) {
2664
0
                if (*format==')')
2665
0
                    break;
2666
0
                if (IS_END_OF_FORMAT(*format))
2667
0
                    return "Unmatched left paren in format "
2668
0
                           "string";
2669
0
                msg = skipitem(&format, p_va, flags);
2670
0
                if (msg)
2671
0
                    return msg;
2672
0
            }
2673
0
            format++;
2674
0
            break;
2675
0
        }
2676
2677
0
    case ')':
2678
0
        return "Unmatched right paren in format string";
2679
2680
0
    default:
2681
0
err:
2682
0
        return "impossible<bad format char>";
2683
2684
231
    }
2685
2686
231
    *p_format = format;
2687
231
    return NULL;
2688
231
}
2689
2690
2691
#undef _PyArg_CheckPositional
2692
2693
int
2694
_PyArg_CheckPositional(const char *name, Py_ssize_t nargs,
2695
                       Py_ssize_t min, Py_ssize_t max)
2696
2.36k
{
2697
2.36k
    assert(min >= 0);
2698
2.36k
    assert(min <= max);
2699
2700
2.36k
    if (nargs < min) {
2701
0
        if (name != NULL)
2702
0
            PyErr_Format(
2703
0
                PyExc_TypeError,
2704
0
                "%.200s expected %s%zd argument%s, got %zd",
2705
0
                name, (min == max ? "" : "at least "), min, min == 1 ? "" : "s", nargs);
2706
0
        else
2707
0
            PyErr_Format(
2708
0
                PyExc_TypeError,
2709
0
                "unpacked tuple should have %s%zd element%s,"
2710
0
                " but has %zd",
2711
0
                (min == max ? "" : "at least "), min, min == 1 ? "" : "s", nargs);
2712
0
        return 0;
2713
0
    }
2714
2715
2.36k
    if (nargs == 0) {
2716
219
        return 1;
2717
219
    }
2718
2719
2.14k
    if (nargs > max) {
2720
0
        if (name != NULL)
2721
0
            PyErr_Format(
2722
0
                PyExc_TypeError,
2723
0
                "%.200s expected %s%zd argument%s, got %zd",
2724
0
                name, (min == max ? "" : "at most "), max, max == 1 ? "" : "s", nargs);
2725
0
        else
2726
0
            PyErr_Format(
2727
0
                PyExc_TypeError,
2728
0
                "unpacked tuple should have %s%zd element%s,"
2729
0
                " but has %zd",
2730
0
                (min == max ? "" : "at most "), max, max == 1 ? "" : "s", nargs);
2731
0
        return 0;
2732
0
    }
2733
2734
2.14k
    return 1;
2735
2.14k
}
2736
2737
static int
2738
unpack_stack(PyObject *const *args, Py_ssize_t nargs, const char *name,
2739
             Py_ssize_t min, Py_ssize_t max, va_list vargs)
2740
2.36k
{
2741
2.36k
    Py_ssize_t i;
2742
2.36k
    PyObject **o;
2743
2744
2.36k
    if (!_PyArg_CheckPositional(name, nargs, min, max)) {
2745
0
        return 0;
2746
0
    }
2747
2748
5.89k
    for (i = 0; i < nargs; i++) {
2749
3.52k
        o = va_arg(vargs, PyObject **);
2750
3.52k
        *o = args[i];
2751
3.52k
    }
2752
2.36k
    return 1;
2753
2.36k
}
2754
2755
int
2756
PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)
2757
2.36k
{
2758
2.36k
    PyObject **stack;
2759
2.36k
    Py_ssize_t nargs;
2760
2.36k
    int retval;
2761
2.36k
    va_list vargs;
2762
2763
2.36k
    if (!PyTuple_Check(args)) {
2764
0
        PyErr_SetString(PyExc_SystemError,
2765
0
            "PyArg_UnpackTuple() argument list is not a tuple");
2766
0
        return 0;
2767
0
    }
2768
2.36k
    stack = _PyTuple_ITEMS(args);
2769
2.36k
    nargs = PyTuple_GET_SIZE(args);
2770
2771
2.36k
#ifdef HAVE_STDARG_PROTOTYPES
2772
2.36k
    va_start(vargs, max);
2773
#else
2774
    va_start(vargs);
2775
#endif
2776
2.36k
    retval = unpack_stack(stack, nargs, name, min, max, vargs);
2777
2.36k
    va_end(vargs);
2778
2.36k
    return retval;
2779
2.36k
}
2780
2781
int
2782
_PyArg_UnpackStack(PyObject *const *args, Py_ssize_t nargs, const char *name,
2783
                   Py_ssize_t min, Py_ssize_t max, ...)
2784
1
{
2785
1
    int retval;
2786
1
    va_list vargs;
2787
2788
1
#ifdef HAVE_STDARG_PROTOTYPES
2789
1
    va_start(vargs, max);
2790
#else
2791
    va_start(vargs);
2792
#endif
2793
1
    retval = unpack_stack(args, nargs, name, min, max, vargs);
2794
1
    va_end(vargs);
2795
1
    return retval;
2796
1
}
2797
2798
2799
#undef _PyArg_NoKeywords
2800
#undef _PyArg_NoPositional
2801
2802
/* For type constructors that don't take keyword args
2803
 *
2804
 * Sets a TypeError and returns 0 if the args/kwargs is
2805
 * not empty, returns 1 otherwise
2806
 */
2807
int
2808
_PyArg_NoKeywords(const char *funcname, PyObject *kwargs)
2809
0
{
2810
0
    if (kwargs == NULL) {
2811
0
        return 1;
2812
0
    }
2813
0
    if (!PyDict_CheckExact(kwargs)) {
2814
0
        PyErr_BadInternalCall();
2815
0
        return 0;
2816
0
    }
2817
0
    if (PyDict_GET_SIZE(kwargs) == 0) {
2818
0
        return 1;
2819
0
    }
2820
2821
0
    PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments",
2822
0
                    funcname);
2823
0
    return 0;
2824
0
}
2825
2826
2827
int
2828
_PyArg_NoPositional(const char *funcname, PyObject *args)
2829
0
{
2830
0
    if (args == NULL)
2831
0
        return 1;
2832
0
    if (!PyTuple_CheckExact(args)) {
2833
0
        PyErr_BadInternalCall();
2834
0
        return 0;
2835
0
    }
2836
0
    if (PyTuple_GET_SIZE(args) == 0)
2837
0
        return 1;
2838
2839
0
    PyErr_Format(PyExc_TypeError, "%.200s() takes no positional arguments",
2840
0
                    funcname);
2841
0
    return 0;
2842
0
}
2843
2844
void
2845
_PyArg_Fini(void)
2846
0
{
2847
0
    struct _PyArg_Parser *tmp, *s = static_arg_parsers;
2848
0
    while (s) {
2849
0
        tmp = s->next;
2850
0
        s->next = NULL;
2851
0
        parser_clear(s);
2852
0
        s = tmp;
2853
0
    }
2854
0
    static_arg_parsers = NULL;
2855
0
}
2856
2857
#ifdef __cplusplus
2858
};
2859
#endif