getargs.c 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990
  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. PyInterpreterState *interp = _PyInterpreterState_GET();
  1754. _PyUnicode_InternImmortal(interp, &str);
  1755. PyTuple_SET_ITEM(kwtuple, i, str);
  1756. }
  1757. return kwtuple;
  1758. }
  1759. static int
  1760. _parser_init(struct _PyArg_Parser *parser)
  1761. {
  1762. const char * const *keywords = parser->keywords;
  1763. assert(keywords != NULL);
  1764. assert(parser->pos == 0 &&
  1765. (parser->format == NULL || parser->fname == NULL) &&
  1766. parser->custom_msg == NULL &&
  1767. parser->min == 0 &&
  1768. parser->max == 0);
  1769. int len, pos;
  1770. if (scan_keywords(keywords, &len, &pos) < 0) {
  1771. return 0;
  1772. }
  1773. const char *fname, *custommsg = NULL;
  1774. int min = 0, max = 0;
  1775. if (parser->format) {
  1776. assert(parser->fname == NULL);
  1777. if (parse_format(parser->format, len, pos,
  1778. &fname, &custommsg, &min, &max) < 0) {
  1779. return 0;
  1780. }
  1781. }
  1782. else {
  1783. assert(parser->fname != NULL);
  1784. fname = parser->fname;
  1785. }
  1786. int owned;
  1787. PyObject *kwtuple = parser->kwtuple;
  1788. if (kwtuple == NULL) {
  1789. /* We may temporarily switch to the main interpreter to avoid
  1790. * creating a tuple that could outlive its owning interpreter. */
  1791. PyThreadState *save_tstate = NULL;
  1792. PyThreadState *temp_tstate = NULL;
  1793. if (!_Py_IsMainInterpreter(PyInterpreterState_Get())) {
  1794. temp_tstate = PyThreadState_New(_PyInterpreterState_Main());
  1795. if (temp_tstate == NULL) {
  1796. return -1;
  1797. }
  1798. save_tstate = PyThreadState_Swap(temp_tstate);
  1799. }
  1800. kwtuple = new_kwtuple(keywords, len, pos);
  1801. if (temp_tstate != NULL) {
  1802. PyThreadState_Clear(temp_tstate);
  1803. (void)PyThreadState_Swap(save_tstate);
  1804. PyThreadState_Delete(temp_tstate);
  1805. }
  1806. if (kwtuple == NULL) {
  1807. return 0;
  1808. }
  1809. owned = 1;
  1810. }
  1811. else {
  1812. owned = 0;
  1813. }
  1814. parser->pos = pos;
  1815. parser->fname = fname;
  1816. parser->custom_msg = custommsg;
  1817. parser->min = min;
  1818. parser->max = max;
  1819. parser->kwtuple = kwtuple;
  1820. parser->initialized = owned ? 1 : -1;
  1821. assert(parser->next == NULL);
  1822. parser->next = _PyRuntime.getargs.static_parsers;
  1823. _PyRuntime.getargs.static_parsers = parser;
  1824. return 1;
  1825. }
  1826. static int
  1827. parser_init(struct _PyArg_Parser *parser)
  1828. {
  1829. // volatile as it can be modified by other threads
  1830. // and should not be optimized or reordered by compiler
  1831. if (*((volatile int *)&parser->initialized)) {
  1832. assert(parser->kwtuple != NULL);
  1833. return 1;
  1834. }
  1835. PyThread_acquire_lock(_PyRuntime.getargs.mutex, WAIT_LOCK);
  1836. // Check again if another thread initialized the parser
  1837. // while we were waiting for the lock.
  1838. if (*((volatile int *)&parser->initialized)) {
  1839. assert(parser->kwtuple != NULL);
  1840. PyThread_release_lock(_PyRuntime.getargs.mutex);
  1841. return 1;
  1842. }
  1843. int ret = _parser_init(parser);
  1844. PyThread_release_lock(_PyRuntime.getargs.mutex);
  1845. return ret;
  1846. }
  1847. static void
  1848. parser_clear(struct _PyArg_Parser *parser)
  1849. {
  1850. if (parser->initialized == 1) {
  1851. Py_CLEAR(parser->kwtuple);
  1852. }
  1853. if (parser->format) {
  1854. parser->fname = NULL;
  1855. }
  1856. else {
  1857. assert(parser->fname != NULL);
  1858. }
  1859. parser->custom_msg = NULL;
  1860. parser->pos = 0;
  1861. parser->min = 0;
  1862. parser->max = 0;
  1863. parser->initialized = 0;
  1864. }
  1865. static PyObject*
  1866. find_keyword(PyObject *kwnames, PyObject *const *kwstack, PyObject *key)
  1867. {
  1868. Py_ssize_t i, nkwargs;
  1869. nkwargs = PyTuple_GET_SIZE(kwnames);
  1870. for (i = 0; i < nkwargs; i++) {
  1871. PyObject *kwname = PyTuple_GET_ITEM(kwnames, i);
  1872. /* kwname == key will normally find a match in since keyword keys
  1873. should be interned strings; if not retry below in a new loop. */
  1874. if (kwname == key) {
  1875. return kwstack[i];
  1876. }
  1877. }
  1878. for (i = 0; i < nkwargs; i++) {
  1879. PyObject *kwname = PyTuple_GET_ITEM(kwnames, i);
  1880. assert(PyUnicode_Check(kwname));
  1881. if (_PyUnicode_EQ(kwname, key)) {
  1882. return kwstack[i];
  1883. }
  1884. }
  1885. return NULL;
  1886. }
  1887. static int
  1888. vgetargskeywordsfast_impl(PyObject *const *args, Py_ssize_t nargs,
  1889. PyObject *kwargs, PyObject *kwnames,
  1890. struct _PyArg_Parser *parser,
  1891. va_list *p_va, int flags)
  1892. {
  1893. PyObject *kwtuple;
  1894. char msgbuf[512];
  1895. int levels[32];
  1896. const char *format;
  1897. const char *msg;
  1898. PyObject *keyword;
  1899. int i, pos, len;
  1900. Py_ssize_t nkwargs;
  1901. PyObject *current_arg;
  1902. freelistentry_t static_entries[STATIC_FREELIST_ENTRIES];
  1903. freelist_t freelist;
  1904. PyObject *const *kwstack = NULL;
  1905. freelist.entries = static_entries;
  1906. freelist.first_available = 0;
  1907. freelist.entries_malloced = 0;
  1908. assert(kwargs == NULL || PyDict_Check(kwargs));
  1909. assert(kwargs == NULL || kwnames == NULL);
  1910. assert(p_va != NULL);
  1911. if (parser == NULL) {
  1912. PyErr_BadInternalCall();
  1913. return 0;
  1914. }
  1915. if (kwnames != NULL && !PyTuple_Check(kwnames)) {
  1916. PyErr_BadInternalCall();
  1917. return 0;
  1918. }
  1919. if (!parser_init(parser)) {
  1920. return 0;
  1921. }
  1922. kwtuple = parser->kwtuple;
  1923. pos = parser->pos;
  1924. len = pos + (int)PyTuple_GET_SIZE(kwtuple);
  1925. if (len > STATIC_FREELIST_ENTRIES) {
  1926. freelist.entries = PyMem_NEW(freelistentry_t, len);
  1927. if (freelist.entries == NULL) {
  1928. PyErr_NoMemory();
  1929. return 0;
  1930. }
  1931. freelist.entries_malloced = 1;
  1932. }
  1933. if (kwargs != NULL) {
  1934. nkwargs = PyDict_GET_SIZE(kwargs);
  1935. }
  1936. else if (kwnames != NULL) {
  1937. nkwargs = PyTuple_GET_SIZE(kwnames);
  1938. kwstack = args + nargs;
  1939. }
  1940. else {
  1941. nkwargs = 0;
  1942. }
  1943. if (nargs + nkwargs > len) {
  1944. /* Adding "keyword" (when nargs == 0) prevents producing wrong error
  1945. messages in some special cases (see bpo-31229). */
  1946. PyErr_Format(PyExc_TypeError,
  1947. "%.200s%s takes at most %d %sargument%s (%zd given)",
  1948. (parser->fname == NULL) ? "function" : parser->fname,
  1949. (parser->fname == NULL) ? "" : "()",
  1950. len,
  1951. (nargs == 0) ? "keyword " : "",
  1952. (len == 1) ? "" : "s",
  1953. nargs + nkwargs);
  1954. return cleanreturn(0, &freelist);
  1955. }
  1956. if (parser->max < nargs) {
  1957. if (parser->max == 0) {
  1958. PyErr_Format(PyExc_TypeError,
  1959. "%.200s%s takes no positional arguments",
  1960. (parser->fname == NULL) ? "function" : parser->fname,
  1961. (parser->fname == NULL) ? "" : "()");
  1962. }
  1963. else {
  1964. PyErr_Format(PyExc_TypeError,
  1965. "%.200s%s takes %s %d positional argument%s (%zd given)",
  1966. (parser->fname == NULL) ? "function" : parser->fname,
  1967. (parser->fname == NULL) ? "" : "()",
  1968. (parser->min < parser->max) ? "at most" : "exactly",
  1969. parser->max,
  1970. parser->max == 1 ? "" : "s",
  1971. nargs);
  1972. }
  1973. return cleanreturn(0, &freelist);
  1974. }
  1975. format = parser->format;
  1976. assert(format != NULL || len == 0);
  1977. /* convert tuple args and keyword args in same loop, using kwtuple to drive process */
  1978. for (i = 0; i < len; i++) {
  1979. if (*format == '|') {
  1980. format++;
  1981. }
  1982. if (*format == '$') {
  1983. format++;
  1984. }
  1985. assert(!IS_END_OF_FORMAT(*format));
  1986. if (i < nargs) {
  1987. current_arg = args[i];
  1988. }
  1989. else if (nkwargs && i >= pos) {
  1990. keyword = PyTuple_GET_ITEM(kwtuple, i - pos);
  1991. if (kwargs != NULL) {
  1992. current_arg = PyDict_GetItemWithError(kwargs, keyword);
  1993. if (!current_arg && PyErr_Occurred()) {
  1994. return cleanreturn(0, &freelist);
  1995. }
  1996. }
  1997. else {
  1998. current_arg = find_keyword(kwnames, kwstack, keyword);
  1999. }
  2000. if (current_arg) {
  2001. --nkwargs;
  2002. }
  2003. }
  2004. else {
  2005. current_arg = NULL;
  2006. }
  2007. if (current_arg) {
  2008. msg = convertitem(current_arg, &format, p_va, flags,
  2009. levels, msgbuf, sizeof(msgbuf), &freelist);
  2010. if (msg) {
  2011. seterror(i+1, msg, levels, parser->fname, parser->custom_msg);
  2012. return cleanreturn(0, &freelist);
  2013. }
  2014. continue;
  2015. }
  2016. if (i < parser->min) {
  2017. /* Less arguments than required */
  2018. if (i < pos) {
  2019. Py_ssize_t min = Py_MIN(pos, parser->min);
  2020. PyErr_Format(PyExc_TypeError,
  2021. "%.200s%s takes %s %d positional argument%s"
  2022. " (%zd given)",
  2023. (parser->fname == NULL) ? "function" : parser->fname,
  2024. (parser->fname == NULL) ? "" : "()",
  2025. min < parser->max ? "at least" : "exactly",
  2026. min,
  2027. min == 1 ? "" : "s",
  2028. nargs);
  2029. }
  2030. else {
  2031. keyword = PyTuple_GET_ITEM(kwtuple, i - pos);
  2032. PyErr_Format(PyExc_TypeError, "%.200s%s missing required "
  2033. "argument '%U' (pos %d)",
  2034. (parser->fname == NULL) ? "function" : parser->fname,
  2035. (parser->fname == NULL) ? "" : "()",
  2036. keyword, i+1);
  2037. }
  2038. return cleanreturn(0, &freelist);
  2039. }
  2040. /* current code reports success when all required args
  2041. * fulfilled and no keyword args left, with no further
  2042. * validation. XXX Maybe skip this in debug build ?
  2043. */
  2044. if (!nkwargs) {
  2045. return cleanreturn(1, &freelist);
  2046. }
  2047. /* We are into optional args, skip through to any remaining
  2048. * keyword args */
  2049. msg = skipitem(&format, p_va, flags);
  2050. assert(msg == NULL);
  2051. }
  2052. assert(IS_END_OF_FORMAT(*format) || (*format == '|') || (*format == '$'));
  2053. if (nkwargs > 0) {
  2054. /* make sure there are no arguments given by name and position */
  2055. for (i = pos; i < nargs; i++) {
  2056. keyword = PyTuple_GET_ITEM(kwtuple, i - pos);
  2057. if (kwargs != NULL) {
  2058. current_arg = PyDict_GetItemWithError(kwargs, keyword);
  2059. if (!current_arg && PyErr_Occurred()) {
  2060. return cleanreturn(0, &freelist);
  2061. }
  2062. }
  2063. else {
  2064. current_arg = find_keyword(kwnames, kwstack, keyword);
  2065. }
  2066. if (current_arg) {
  2067. /* arg present in tuple and in dict */
  2068. PyErr_Format(PyExc_TypeError,
  2069. "argument for %.200s%s given by name ('%U') "
  2070. "and position (%d)",
  2071. (parser->fname == NULL) ? "function" : parser->fname,
  2072. (parser->fname == NULL) ? "" : "()",
  2073. keyword, i+1);
  2074. return cleanreturn(0, &freelist);
  2075. }
  2076. }
  2077. error_unexpected_keyword_arg(kwargs, kwnames, kwtuple, parser->fname);
  2078. return cleanreturn(0, &freelist);
  2079. }
  2080. return cleanreturn(1, &freelist);
  2081. }
  2082. static int
  2083. vgetargskeywordsfast(PyObject *args, PyObject *keywords,
  2084. struct _PyArg_Parser *parser, va_list *p_va, int flags)
  2085. {
  2086. PyObject **stack;
  2087. Py_ssize_t nargs;
  2088. if (args == NULL
  2089. || !PyTuple_Check(args)
  2090. || (keywords != NULL && !PyDict_Check(keywords)))
  2091. {
  2092. PyErr_BadInternalCall();
  2093. return 0;
  2094. }
  2095. stack = _PyTuple_ITEMS(args);
  2096. nargs = PyTuple_GET_SIZE(args);
  2097. return vgetargskeywordsfast_impl(stack, nargs, keywords, NULL,
  2098. parser, p_va, flags);
  2099. }
  2100. #undef _PyArg_UnpackKeywords
  2101. PyObject * const *
  2102. _PyArg_UnpackKeywords(PyObject *const *args, Py_ssize_t nargs,
  2103. PyObject *kwargs, PyObject *kwnames,
  2104. struct _PyArg_Parser *parser,
  2105. int minpos, int maxpos, int minkw,
  2106. PyObject **buf)
  2107. {
  2108. PyObject *kwtuple;
  2109. PyObject *keyword;
  2110. int i, posonly, minposonly, maxargs;
  2111. int reqlimit = minkw ? maxpos + minkw : minpos;
  2112. Py_ssize_t nkwargs;
  2113. PyObject *current_arg;
  2114. PyObject * const *kwstack = NULL;
  2115. assert(kwargs == NULL || PyDict_Check(kwargs));
  2116. assert(kwargs == NULL || kwnames == NULL);
  2117. if (parser == NULL) {
  2118. PyErr_BadInternalCall();
  2119. return NULL;
  2120. }
  2121. if (kwnames != NULL && !PyTuple_Check(kwnames)) {
  2122. PyErr_BadInternalCall();
  2123. return NULL;
  2124. }
  2125. if (args == NULL && nargs == 0) {
  2126. args = buf;
  2127. }
  2128. if (!parser_init(parser)) {
  2129. return NULL;
  2130. }
  2131. kwtuple = parser->kwtuple;
  2132. posonly = parser->pos;
  2133. minposonly = Py_MIN(posonly, minpos);
  2134. maxargs = posonly + (int)PyTuple_GET_SIZE(kwtuple);
  2135. if (kwargs != NULL) {
  2136. nkwargs = PyDict_GET_SIZE(kwargs);
  2137. }
  2138. else if (kwnames != NULL) {
  2139. nkwargs = PyTuple_GET_SIZE(kwnames);
  2140. kwstack = args + nargs;
  2141. }
  2142. else {
  2143. nkwargs = 0;
  2144. }
  2145. if (nkwargs == 0 && minkw == 0 && minpos <= nargs && nargs <= maxpos) {
  2146. /* Fast path. */
  2147. return args;
  2148. }
  2149. if (nargs + nkwargs > maxargs) {
  2150. /* Adding "keyword" (when nargs == 0) prevents producing wrong error
  2151. messages in some special cases (see bpo-31229). */
  2152. PyErr_Format(PyExc_TypeError,
  2153. "%.200s%s takes at most %d %sargument%s (%zd given)",
  2154. (parser->fname == NULL) ? "function" : parser->fname,
  2155. (parser->fname == NULL) ? "" : "()",
  2156. maxargs,
  2157. (nargs == 0) ? "keyword " : "",
  2158. (maxargs == 1) ? "" : "s",
  2159. nargs + nkwargs);
  2160. return NULL;
  2161. }
  2162. if (nargs > maxpos) {
  2163. if (maxpos == 0) {
  2164. PyErr_Format(PyExc_TypeError,
  2165. "%.200s%s takes no positional arguments",
  2166. (parser->fname == NULL) ? "function" : parser->fname,
  2167. (parser->fname == NULL) ? "" : "()");
  2168. }
  2169. else {
  2170. PyErr_Format(PyExc_TypeError,
  2171. "%.200s%s takes %s %d positional argument%s (%zd given)",
  2172. (parser->fname == NULL) ? "function" : parser->fname,
  2173. (parser->fname == NULL) ? "" : "()",
  2174. (minpos < maxpos) ? "at most" : "exactly",
  2175. maxpos,
  2176. (maxpos == 1) ? "" : "s",
  2177. nargs);
  2178. }
  2179. return NULL;
  2180. }
  2181. if (nargs < minposonly) {
  2182. PyErr_Format(PyExc_TypeError,
  2183. "%.200s%s takes %s %d positional argument%s"
  2184. " (%zd given)",
  2185. (parser->fname == NULL) ? "function" : parser->fname,
  2186. (parser->fname == NULL) ? "" : "()",
  2187. minposonly < maxpos ? "at least" : "exactly",
  2188. minposonly,
  2189. minposonly == 1 ? "" : "s",
  2190. nargs);
  2191. return NULL;
  2192. }
  2193. /* copy tuple args */
  2194. for (i = 0; i < nargs; i++) {
  2195. buf[i] = args[i];
  2196. }
  2197. /* copy keyword args using kwtuple to drive process */
  2198. for (i = Py_MAX((int)nargs, posonly); i < maxargs; i++) {
  2199. if (nkwargs) {
  2200. keyword = PyTuple_GET_ITEM(kwtuple, i - posonly);
  2201. if (kwargs != NULL) {
  2202. current_arg = PyDict_GetItemWithError(kwargs, keyword);
  2203. if (!current_arg && PyErr_Occurred()) {
  2204. return NULL;
  2205. }
  2206. }
  2207. else {
  2208. current_arg = find_keyword(kwnames, kwstack, keyword);
  2209. }
  2210. }
  2211. else if (i >= reqlimit) {
  2212. break;
  2213. }
  2214. else {
  2215. current_arg = NULL;
  2216. }
  2217. buf[i] = current_arg;
  2218. if (current_arg) {
  2219. --nkwargs;
  2220. }
  2221. else if (i < minpos || (maxpos <= i && i < reqlimit)) {
  2222. /* Less arguments than required */
  2223. keyword = PyTuple_GET_ITEM(kwtuple, i - posonly);
  2224. PyErr_Format(PyExc_TypeError, "%.200s%s missing required "
  2225. "argument '%U' (pos %d)",
  2226. (parser->fname == NULL) ? "function" : parser->fname,
  2227. (parser->fname == NULL) ? "" : "()",
  2228. keyword, i+1);
  2229. return NULL;
  2230. }
  2231. }
  2232. if (nkwargs > 0) {
  2233. /* make sure there are no arguments given by name and position */
  2234. for (i = posonly; i < nargs; i++) {
  2235. keyword = PyTuple_GET_ITEM(kwtuple, i - posonly);
  2236. if (kwargs != NULL) {
  2237. current_arg = PyDict_GetItemWithError(kwargs, keyword);
  2238. if (!current_arg && PyErr_Occurred()) {
  2239. return NULL;
  2240. }
  2241. }
  2242. else {
  2243. current_arg = find_keyword(kwnames, kwstack, keyword);
  2244. }
  2245. if (current_arg) {
  2246. /* arg present in tuple and in dict */
  2247. PyErr_Format(PyExc_TypeError,
  2248. "argument for %.200s%s given by name ('%U') "
  2249. "and position (%d)",
  2250. (parser->fname == NULL) ? "function" : parser->fname,
  2251. (parser->fname == NULL) ? "" : "()",
  2252. keyword, i+1);
  2253. return NULL;
  2254. }
  2255. }
  2256. error_unexpected_keyword_arg(kwargs, kwnames, kwtuple, parser->fname);
  2257. return NULL;
  2258. }
  2259. return buf;
  2260. }
  2261. PyObject * const *
  2262. _PyArg_UnpackKeywordsWithVararg(PyObject *const *args, Py_ssize_t nargs,
  2263. PyObject *kwargs, PyObject *kwnames,
  2264. struct _PyArg_Parser *parser,
  2265. int minpos, int maxpos, int minkw,
  2266. int vararg, PyObject **buf)
  2267. {
  2268. PyObject *kwtuple;
  2269. PyObject *keyword;
  2270. Py_ssize_t varargssize = 0;
  2271. int i, posonly, minposonly, maxargs;
  2272. int reqlimit = minkw ? maxpos + minkw : minpos;
  2273. Py_ssize_t nkwargs;
  2274. PyObject *current_arg;
  2275. PyObject * const *kwstack = NULL;
  2276. assert(kwargs == NULL || PyDict_Check(kwargs));
  2277. assert(kwargs == NULL || kwnames == NULL);
  2278. if (parser == NULL) {
  2279. PyErr_BadInternalCall();
  2280. return NULL;
  2281. }
  2282. if (kwnames != NULL && !PyTuple_Check(kwnames)) {
  2283. PyErr_BadInternalCall();
  2284. return NULL;
  2285. }
  2286. if (args == NULL && nargs == 0) {
  2287. args = buf;
  2288. }
  2289. if (!parser_init(parser)) {
  2290. return NULL;
  2291. }
  2292. kwtuple = parser->kwtuple;
  2293. posonly = parser->pos;
  2294. minposonly = Py_MIN(posonly, minpos);
  2295. maxargs = posonly + (int)PyTuple_GET_SIZE(kwtuple);
  2296. if (kwargs != NULL) {
  2297. nkwargs = PyDict_GET_SIZE(kwargs);
  2298. }
  2299. else if (kwnames != NULL) {
  2300. nkwargs = PyTuple_GET_SIZE(kwnames);
  2301. kwstack = args + nargs;
  2302. }
  2303. else {
  2304. nkwargs = 0;
  2305. }
  2306. if (nargs < minposonly) {
  2307. PyErr_Format(PyExc_TypeError,
  2308. "%.200s%s takes %s %d positional argument%s"
  2309. " (%zd given)",
  2310. (parser->fname == NULL) ? "function" : parser->fname,
  2311. (parser->fname == NULL) ? "" : "()",
  2312. minposonly < maxpos ? "at least" : "exactly",
  2313. minposonly,
  2314. minposonly == 1 ? "" : "s",
  2315. nargs);
  2316. return NULL;
  2317. }
  2318. /* create varargs tuple */
  2319. varargssize = nargs - maxpos;
  2320. if (varargssize < 0) {
  2321. varargssize = 0;
  2322. }
  2323. buf[vararg] = PyTuple_New(varargssize);
  2324. if (!buf[vararg]) {
  2325. return NULL;
  2326. }
  2327. /* copy tuple args */
  2328. for (i = 0; i < nargs; i++) {
  2329. if (i >= vararg) {
  2330. PyTuple_SET_ITEM(buf[vararg], i - vararg, Py_NewRef(args[i]));
  2331. continue;
  2332. }
  2333. else {
  2334. buf[i] = args[i];
  2335. }
  2336. }
  2337. /* copy keyword args using kwtuple to drive process */
  2338. for (i = Py_MAX((int)nargs, posonly) -
  2339. Py_SAFE_DOWNCAST(varargssize, Py_ssize_t, int); i < maxargs; i++) {
  2340. if (nkwargs) {
  2341. keyword = PyTuple_GET_ITEM(kwtuple, i - posonly);
  2342. if (kwargs != NULL) {
  2343. current_arg = PyDict_GetItemWithError(kwargs, keyword);
  2344. if (!current_arg && PyErr_Occurred()) {
  2345. goto exit;
  2346. }
  2347. }
  2348. else {
  2349. current_arg = find_keyword(kwnames, kwstack, keyword);
  2350. }
  2351. }
  2352. else {
  2353. current_arg = NULL;
  2354. }
  2355. /* If an arguments is passed in as a keyword argument,
  2356. * it should be placed before `buf[vararg]`.
  2357. *
  2358. * For example:
  2359. * def f(a, /, b, *args):
  2360. * pass
  2361. * f(1, b=2)
  2362. *
  2363. * This `buf` array should be: [1, 2, NULL].
  2364. * In this case, nargs < vararg.
  2365. *
  2366. * Otherwise, we leave a place at `buf[vararg]` for vararg tuple
  2367. * so the index is `i + 1`. */
  2368. if (i < vararg) {
  2369. buf[i] = current_arg;
  2370. }
  2371. else {
  2372. buf[i + 1] = current_arg;
  2373. }
  2374. if (current_arg) {
  2375. --nkwargs;
  2376. }
  2377. else if (i < minpos || (maxpos <= i && i < reqlimit)) {
  2378. /* Less arguments than required */
  2379. keyword = PyTuple_GET_ITEM(kwtuple, i - posonly);
  2380. PyErr_Format(PyExc_TypeError, "%.200s%s missing required "
  2381. "argument '%U' (pos %d)",
  2382. (parser->fname == NULL) ? "function" : parser->fname,
  2383. (parser->fname == NULL) ? "" : "()",
  2384. keyword, i+1);
  2385. goto exit;
  2386. }
  2387. }
  2388. if (nkwargs > 0) {
  2389. error_unexpected_keyword_arg(kwargs, kwnames, kwtuple, parser->fname);
  2390. goto exit;
  2391. }
  2392. return buf;
  2393. exit:
  2394. Py_XDECREF(buf[vararg]);
  2395. return NULL;
  2396. }
  2397. static const char *
  2398. skipitem(const char **p_format, va_list *p_va, int flags)
  2399. {
  2400. const char *format = *p_format;
  2401. char c = *format++;
  2402. switch (c) {
  2403. /*
  2404. * codes that take a single data pointer as an argument
  2405. * (the type of the pointer is irrelevant)
  2406. */
  2407. case 'b': /* byte -- very short int */
  2408. case 'B': /* byte as bitfield */
  2409. case 'h': /* short int */
  2410. case 'H': /* short int as bitfield */
  2411. case 'i': /* int */
  2412. case 'I': /* int sized bitfield */
  2413. case 'l': /* long int */
  2414. case 'k': /* long int sized bitfield */
  2415. case 'L': /* long long */
  2416. case 'K': /* long long sized bitfield */
  2417. case 'n': /* Py_ssize_t */
  2418. case 'f': /* float */
  2419. case 'd': /* double */
  2420. case 'D': /* complex double */
  2421. case 'c': /* char */
  2422. case 'C': /* unicode char */
  2423. case 'p': /* boolean predicate */
  2424. case 'S': /* string object */
  2425. case 'Y': /* string object */
  2426. case 'U': /* unicode string object */
  2427. {
  2428. if (p_va != NULL) {
  2429. (void) va_arg(*p_va, void *);
  2430. }
  2431. break;
  2432. }
  2433. /* string codes */
  2434. case 'e': /* string with encoding */
  2435. {
  2436. if (p_va != NULL) {
  2437. (void) va_arg(*p_va, const char *);
  2438. }
  2439. if (!(*format == 's' || *format == 't'))
  2440. /* after 'e', only 's' and 't' is allowed */
  2441. goto err;
  2442. format++;
  2443. }
  2444. /* fall through */
  2445. case 's': /* string */
  2446. case 'z': /* string or None */
  2447. case 'y': /* bytes */
  2448. case 'w': /* buffer, read-write */
  2449. {
  2450. if (p_va != NULL) {
  2451. (void) va_arg(*p_va, char **);
  2452. }
  2453. if (*format == '#') {
  2454. if (p_va != NULL) {
  2455. if (!(flags & FLAG_SIZE_T)) {
  2456. return "PY_SSIZE_T_CLEAN macro must be defined for '#' formats";
  2457. }
  2458. (void) va_arg(*p_va, Py_ssize_t *);
  2459. }
  2460. format++;
  2461. } else if ((c == 's' || c == 'z' || c == 'y' || c == 'w')
  2462. && *format == '*')
  2463. {
  2464. format++;
  2465. }
  2466. break;
  2467. }
  2468. case 'O': /* object */
  2469. {
  2470. if (*format == '!') {
  2471. format++;
  2472. if (p_va != NULL) {
  2473. (void) va_arg(*p_va, PyTypeObject*);
  2474. (void) va_arg(*p_va, PyObject **);
  2475. }
  2476. }
  2477. else if (*format == '&') {
  2478. typedef int (*converter)(PyObject *, void *);
  2479. if (p_va != NULL) {
  2480. (void) va_arg(*p_va, converter);
  2481. (void) va_arg(*p_va, void *);
  2482. }
  2483. format++;
  2484. }
  2485. else {
  2486. if (p_va != NULL) {
  2487. (void) va_arg(*p_va, PyObject **);
  2488. }
  2489. }
  2490. break;
  2491. }
  2492. case '(': /* bypass tuple, not handled at all previously */
  2493. {
  2494. const char *msg;
  2495. for (;;) {
  2496. if (*format==')')
  2497. break;
  2498. if (IS_END_OF_FORMAT(*format))
  2499. return "Unmatched left paren in format "
  2500. "string";
  2501. msg = skipitem(&format, p_va, flags);
  2502. if (msg)
  2503. return msg;
  2504. }
  2505. format++;
  2506. break;
  2507. }
  2508. case ')':
  2509. return "Unmatched right paren in format string";
  2510. default:
  2511. err:
  2512. return "impossible<bad format char>";
  2513. }
  2514. *p_format = format;
  2515. return NULL;
  2516. }
  2517. #undef _PyArg_CheckPositional
  2518. int
  2519. _PyArg_CheckPositional(const char *name, Py_ssize_t nargs,
  2520. Py_ssize_t min, Py_ssize_t max)
  2521. {
  2522. assert(min >= 0);
  2523. assert(min <= max);
  2524. if (nargs < min) {
  2525. if (name != NULL)
  2526. PyErr_Format(
  2527. PyExc_TypeError,
  2528. "%.200s expected %s%zd argument%s, got %zd",
  2529. name, (min == max ? "" : "at least "), min, min == 1 ? "" : "s", nargs);
  2530. else
  2531. PyErr_Format(
  2532. PyExc_TypeError,
  2533. "unpacked tuple should have %s%zd element%s,"
  2534. " but has %zd",
  2535. (min == max ? "" : "at least "), min, min == 1 ? "" : "s", nargs);
  2536. return 0;
  2537. }
  2538. if (nargs == 0) {
  2539. return 1;
  2540. }
  2541. if (nargs > max) {
  2542. if (name != NULL)
  2543. PyErr_Format(
  2544. PyExc_TypeError,
  2545. "%.200s expected %s%zd argument%s, got %zd",
  2546. name, (min == max ? "" : "at most "), max, max == 1 ? "" : "s", nargs);
  2547. else
  2548. PyErr_Format(
  2549. PyExc_TypeError,
  2550. "unpacked tuple should have %s%zd element%s,"
  2551. " but has %zd",
  2552. (min == max ? "" : "at most "), max, max == 1 ? "" : "s", nargs);
  2553. return 0;
  2554. }
  2555. return 1;
  2556. }
  2557. static int
  2558. unpack_stack(PyObject *const *args, Py_ssize_t nargs, const char *name,
  2559. Py_ssize_t min, Py_ssize_t max, va_list vargs)
  2560. {
  2561. Py_ssize_t i;
  2562. PyObject **o;
  2563. if (!_PyArg_CheckPositional(name, nargs, min, max)) {
  2564. return 0;
  2565. }
  2566. for (i = 0; i < nargs; i++) {
  2567. o = va_arg(vargs, PyObject **);
  2568. *o = args[i];
  2569. }
  2570. return 1;
  2571. }
  2572. int
  2573. PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)
  2574. {
  2575. PyObject **stack;
  2576. Py_ssize_t nargs;
  2577. int retval;
  2578. va_list vargs;
  2579. if (!PyTuple_Check(args)) {
  2580. PyErr_SetString(PyExc_SystemError,
  2581. "PyArg_UnpackTuple() argument list is not a tuple");
  2582. return 0;
  2583. }
  2584. stack = _PyTuple_ITEMS(args);
  2585. nargs = PyTuple_GET_SIZE(args);
  2586. va_start(vargs, max);
  2587. retval = unpack_stack(stack, nargs, name, min, max, vargs);
  2588. va_end(vargs);
  2589. return retval;
  2590. }
  2591. int
  2592. _PyArg_UnpackStack(PyObject *const *args, Py_ssize_t nargs, const char *name,
  2593. Py_ssize_t min, Py_ssize_t max, ...)
  2594. {
  2595. int retval;
  2596. va_list vargs;
  2597. va_start(vargs, max);
  2598. retval = unpack_stack(args, nargs, name, min, max, vargs);
  2599. va_end(vargs);
  2600. return retval;
  2601. }
  2602. #undef _PyArg_NoKeywords
  2603. #undef _PyArg_NoKwnames
  2604. #undef _PyArg_NoPositional
  2605. /* For type constructors that don't take keyword args
  2606. *
  2607. * Sets a TypeError and returns 0 if the args/kwargs is
  2608. * not empty, returns 1 otherwise
  2609. */
  2610. int
  2611. _PyArg_NoKeywords(const char *funcname, PyObject *kwargs)
  2612. {
  2613. if (kwargs == NULL) {
  2614. return 1;
  2615. }
  2616. if (!PyDict_CheckExact(kwargs)) {
  2617. PyErr_BadInternalCall();
  2618. return 0;
  2619. }
  2620. if (PyDict_GET_SIZE(kwargs) == 0) {
  2621. return 1;
  2622. }
  2623. PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments",
  2624. funcname);
  2625. return 0;
  2626. }
  2627. int
  2628. _PyArg_NoPositional(const char *funcname, PyObject *args)
  2629. {
  2630. if (args == NULL)
  2631. return 1;
  2632. if (!PyTuple_CheckExact(args)) {
  2633. PyErr_BadInternalCall();
  2634. return 0;
  2635. }
  2636. if (PyTuple_GET_SIZE(args) == 0)
  2637. return 1;
  2638. PyErr_Format(PyExc_TypeError, "%.200s() takes no positional arguments",
  2639. funcname);
  2640. return 0;
  2641. }
  2642. int
  2643. _PyArg_NoKwnames(const char *funcname, PyObject *kwnames)
  2644. {
  2645. if (kwnames == NULL) {
  2646. return 1;
  2647. }
  2648. assert(PyTuple_CheckExact(kwnames));
  2649. if (PyTuple_GET_SIZE(kwnames) == 0) {
  2650. return 1;
  2651. }
  2652. PyErr_Format(PyExc_TypeError, "%s() takes no keyword arguments", funcname);
  2653. return 0;
  2654. }
  2655. void
  2656. _PyArg_Fini(void)
  2657. {
  2658. struct _PyArg_Parser *tmp, *s = _PyRuntime.getargs.static_parsers;
  2659. while (s) {
  2660. tmp = s->next;
  2661. s->next = NULL;
  2662. parser_clear(s);
  2663. s = tmp;
  2664. }
  2665. _PyRuntime.getargs.static_parsers = NULL;
  2666. }
  2667. #ifdef __cplusplus
  2668. };
  2669. #endif