Coverage Report

Created: 2025-07-18 06:09

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