getargs.c 89 KB

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