pyexpat.c 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201
  1. #include "Python.h"
  2. #include <ctype.h>
  3. #include <stdbool.h>
  4. #include "structmember.h" // PyMemberDef
  5. #include "expat.h"
  6. #include "pyexpat.h"
  7. /* Do not emit Clinic output to a file as that wreaks havoc with conditionally
  8. included methods. */
  9. /*[clinic input]
  10. module pyexpat
  11. [clinic start generated code]*/
  12. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=b168d503a4490c15]*/
  13. #define XML_COMBINED_VERSION (10000*XML_MAJOR_VERSION+100*XML_MINOR_VERSION+XML_MICRO_VERSION)
  14. static XML_Memory_Handling_Suite ExpatMemoryHandler = {
  15. PyObject_Malloc, PyObject_Realloc, PyObject_Free};
  16. enum HandlerTypes {
  17. StartElement,
  18. EndElement,
  19. ProcessingInstruction,
  20. CharacterData,
  21. UnparsedEntityDecl,
  22. NotationDecl,
  23. StartNamespaceDecl,
  24. EndNamespaceDecl,
  25. Comment,
  26. StartCdataSection,
  27. EndCdataSection,
  28. Default,
  29. DefaultHandlerExpand,
  30. NotStandalone,
  31. ExternalEntityRef,
  32. StartDoctypeDecl,
  33. EndDoctypeDecl,
  34. EntityDecl,
  35. XmlDecl,
  36. ElementDecl,
  37. AttlistDecl,
  38. #if XML_COMBINED_VERSION >= 19504
  39. SkippedEntity,
  40. #endif
  41. _DummyDecl
  42. };
  43. typedef struct {
  44. PyTypeObject *xml_parse_type;
  45. PyObject *error;
  46. PyObject *str_read;
  47. } pyexpat_state;
  48. static inline pyexpat_state*
  49. pyexpat_get_state(PyObject *module)
  50. {
  51. void *state = PyModule_GetState(module);
  52. assert(state != NULL);
  53. return (pyexpat_state *)state;
  54. }
  55. /* ----------------------------------------------------- */
  56. /* Declarations for objects of type xmlparser */
  57. typedef struct {
  58. PyObject_HEAD
  59. XML_Parser itself;
  60. int ordered_attributes; /* Return attributes as a list. */
  61. int specified_attributes; /* Report only specified attributes. */
  62. int in_callback; /* Is a callback active? */
  63. int ns_prefixes; /* Namespace-triplets mode? */
  64. XML_Char *buffer; /* Buffer used when accumulating characters */
  65. /* NULL if not enabled */
  66. int buffer_size; /* Size of buffer, in XML_Char units */
  67. int buffer_used; /* Buffer units in use */
  68. bool reparse_deferral_enabled; /* Whether to defer reparsing of
  69. unfinished XML tokens; a de-facto cache of
  70. what Expat has the authority on, for lack
  71. of a getter API function
  72. "XML_GetReparseDeferralEnabled" in Expat
  73. 2.6.0 */
  74. PyObject *intern; /* Dictionary to intern strings */
  75. PyObject **handlers;
  76. } xmlparseobject;
  77. #include "clinic/pyexpat.c.h"
  78. #define CHARACTER_DATA_BUFFER_SIZE 8192
  79. typedef void (*xmlhandlersetter)(XML_Parser self, void *meth);
  80. typedef void* xmlhandler;
  81. struct HandlerInfo {
  82. const char *name;
  83. xmlhandlersetter setter;
  84. xmlhandler handler;
  85. PyGetSetDef getset;
  86. };
  87. static struct HandlerInfo handler_info[64];
  88. /* Set an integer attribute on the error object; return true on success,
  89. * false on an exception.
  90. */
  91. static int
  92. set_error_attr(PyObject *err, const char *name, int value)
  93. {
  94. PyObject *v = PyLong_FromLong(value);
  95. if (v == NULL || PyObject_SetAttrString(err, name, v) == -1) {
  96. Py_XDECREF(v);
  97. return 0;
  98. }
  99. Py_DECREF(v);
  100. return 1;
  101. }
  102. /* Build and set an Expat exception, including positioning
  103. * information. Always returns NULL.
  104. */
  105. static PyObject *
  106. set_error(pyexpat_state *state, xmlparseobject *self, enum XML_Error code)
  107. {
  108. PyObject *err;
  109. PyObject *buffer;
  110. XML_Parser parser = self->itself;
  111. int lineno = XML_GetErrorLineNumber(parser);
  112. int column = XML_GetErrorColumnNumber(parser);
  113. buffer = PyUnicode_FromFormat("%s: line %i, column %i",
  114. XML_ErrorString(code), lineno, column);
  115. if (buffer == NULL)
  116. return NULL;
  117. err = PyObject_CallOneArg(state->error, buffer);
  118. Py_DECREF(buffer);
  119. if ( err != NULL
  120. && set_error_attr(err, "code", code)
  121. && set_error_attr(err, "offset", column)
  122. && set_error_attr(err, "lineno", lineno)) {
  123. PyErr_SetObject(state->error, err);
  124. }
  125. Py_XDECREF(err);
  126. return NULL;
  127. }
  128. static int
  129. have_handler(xmlparseobject *self, int type)
  130. {
  131. PyObject *handler = self->handlers[type];
  132. return handler != NULL;
  133. }
  134. /* Convert a string of XML_Chars into a Unicode string.
  135. Returns None if str is a null pointer. */
  136. static PyObject *
  137. conv_string_to_unicode(const XML_Char *str)
  138. {
  139. /* XXX currently this code assumes that XML_Char is 8-bit,
  140. and hence in UTF-8. */
  141. /* UTF-8 from Expat, Unicode desired */
  142. if (str == NULL) {
  143. Py_RETURN_NONE;
  144. }
  145. return PyUnicode_DecodeUTF8(str, strlen(str), "strict");
  146. }
  147. static PyObject *
  148. conv_string_len_to_unicode(const XML_Char *str, int len)
  149. {
  150. /* XXX currently this code assumes that XML_Char is 8-bit,
  151. and hence in UTF-8. */
  152. /* UTF-8 from Expat, Unicode desired */
  153. if (str == NULL) {
  154. Py_RETURN_NONE;
  155. }
  156. return PyUnicode_DecodeUTF8((const char *)str, len, "strict");
  157. }
  158. /* Callback routines */
  159. static void clear_handlers(xmlparseobject *self, int initial);
  160. /* This handler is used when an error has been detected, in the hope
  161. that actual parsing can be terminated early. This will only help
  162. if an external entity reference is encountered. */
  163. static int
  164. error_external_entity_ref_handler(XML_Parser parser,
  165. const XML_Char *context,
  166. const XML_Char *base,
  167. const XML_Char *systemId,
  168. const XML_Char *publicId)
  169. {
  170. return 0;
  171. }
  172. /* Dummy character data handler used when an error (exception) has
  173. been detected, and the actual parsing can be terminated early.
  174. This is needed since character data handler can't be safely removed
  175. from within the character data handler, but can be replaced. It is
  176. used only from the character data handler trampoline, and must be
  177. used right after `flag_error()` is called. */
  178. static void
  179. noop_character_data_handler(void *userData, const XML_Char *data, int len)
  180. {
  181. /* Do nothing. */
  182. }
  183. static void
  184. flag_error(xmlparseobject *self)
  185. {
  186. clear_handlers(self, 0);
  187. XML_SetExternalEntityRefHandler(self->itself,
  188. error_external_entity_ref_handler);
  189. }
  190. static PyObject*
  191. call_with_frame(const char *funcname, int lineno, PyObject* func, PyObject* args,
  192. xmlparseobject *self)
  193. {
  194. PyObject *res;
  195. res = PyObject_Call(func, args, NULL);
  196. if (res == NULL) {
  197. _PyTraceback_Add(funcname, __FILE__, lineno);
  198. XML_StopParser(self->itself, XML_FALSE);
  199. }
  200. return res;
  201. }
  202. static PyObject*
  203. string_intern(xmlparseobject *self, const char* str)
  204. {
  205. PyObject *result = conv_string_to_unicode(str);
  206. PyObject *value;
  207. /* result can be NULL if the unicode conversion failed. */
  208. if (!result)
  209. return result;
  210. if (!self->intern)
  211. return result;
  212. value = PyDict_GetItemWithError(self->intern, result);
  213. if (!value) {
  214. if (!PyErr_Occurred() &&
  215. PyDict_SetItem(self->intern, result, result) == 0)
  216. {
  217. return result;
  218. }
  219. else {
  220. Py_DECREF(result);
  221. return NULL;
  222. }
  223. }
  224. Py_INCREF(value);
  225. Py_DECREF(result);
  226. return value;
  227. }
  228. /* Return 0 on success, -1 on exception.
  229. * flag_error() will be called before return if needed.
  230. */
  231. static int
  232. call_character_handler(xmlparseobject *self, const XML_Char *buffer, int len)
  233. {
  234. PyObject *args;
  235. PyObject *temp;
  236. if (!have_handler(self, CharacterData))
  237. return -1;
  238. args = PyTuple_New(1);
  239. if (args == NULL)
  240. return -1;
  241. temp = (conv_string_len_to_unicode(buffer, len));
  242. if (temp == NULL) {
  243. Py_DECREF(args);
  244. flag_error(self);
  245. XML_SetCharacterDataHandler(self->itself,
  246. noop_character_data_handler);
  247. return -1;
  248. }
  249. PyTuple_SET_ITEM(args, 0, temp);
  250. /* temp is now a borrowed reference; consider it unused. */
  251. self->in_callback = 1;
  252. temp = call_with_frame("CharacterData", __LINE__,
  253. self->handlers[CharacterData], args, self);
  254. /* temp is an owned reference again, or NULL */
  255. self->in_callback = 0;
  256. Py_DECREF(args);
  257. if (temp == NULL) {
  258. flag_error(self);
  259. XML_SetCharacterDataHandler(self->itself,
  260. noop_character_data_handler);
  261. return -1;
  262. }
  263. Py_DECREF(temp);
  264. return 0;
  265. }
  266. static int
  267. flush_character_buffer(xmlparseobject *self)
  268. {
  269. int rc;
  270. if (self->buffer == NULL || self->buffer_used == 0)
  271. return 0;
  272. rc = call_character_handler(self, self->buffer, self->buffer_used);
  273. self->buffer_used = 0;
  274. return rc;
  275. }
  276. static void
  277. my_CharacterDataHandler(void *userData, const XML_Char *data, int len)
  278. {
  279. xmlparseobject *self = (xmlparseobject *) userData;
  280. if (PyErr_Occurred())
  281. return;
  282. if (self->buffer == NULL)
  283. call_character_handler(self, data, len);
  284. else {
  285. if ((self->buffer_used + len) > self->buffer_size) {
  286. if (flush_character_buffer(self) < 0)
  287. return;
  288. /* handler might have changed; drop the rest on the floor
  289. * if there isn't a handler anymore
  290. */
  291. if (!have_handler(self, CharacterData))
  292. return;
  293. }
  294. if (len > self->buffer_size) {
  295. call_character_handler(self, data, len);
  296. self->buffer_used = 0;
  297. }
  298. else {
  299. memcpy(self->buffer + self->buffer_used,
  300. data, len * sizeof(XML_Char));
  301. self->buffer_used += len;
  302. }
  303. }
  304. }
  305. static void
  306. my_StartElementHandler(void *userData,
  307. const XML_Char *name, const XML_Char *atts[])
  308. {
  309. xmlparseobject *self = (xmlparseobject *)userData;
  310. if (have_handler(self, StartElement)) {
  311. PyObject *container, *rv, *args;
  312. int i, max;
  313. if (PyErr_Occurred())
  314. return;
  315. if (flush_character_buffer(self) < 0)
  316. return;
  317. /* Set max to the number of slots filled in atts[]; max/2 is
  318. * the number of attributes we need to process.
  319. */
  320. if (self->specified_attributes) {
  321. max = XML_GetSpecifiedAttributeCount(self->itself);
  322. }
  323. else {
  324. max = 0;
  325. while (atts[max] != NULL)
  326. max += 2;
  327. }
  328. /* Build the container. */
  329. if (self->ordered_attributes)
  330. container = PyList_New(max);
  331. else
  332. container = PyDict_New();
  333. if (container == NULL) {
  334. flag_error(self);
  335. return;
  336. }
  337. for (i = 0; i < max; i += 2) {
  338. PyObject *n = string_intern(self, (XML_Char *) atts[i]);
  339. PyObject *v;
  340. if (n == NULL) {
  341. flag_error(self);
  342. Py_DECREF(container);
  343. return;
  344. }
  345. v = conv_string_to_unicode((XML_Char *) atts[i+1]);
  346. if (v == NULL) {
  347. flag_error(self);
  348. Py_DECREF(container);
  349. Py_DECREF(n);
  350. return;
  351. }
  352. if (self->ordered_attributes) {
  353. PyList_SET_ITEM(container, i, n);
  354. PyList_SET_ITEM(container, i+1, v);
  355. }
  356. else if (PyDict_SetItem(container, n, v)) {
  357. flag_error(self);
  358. Py_DECREF(n);
  359. Py_DECREF(v);
  360. Py_DECREF(container);
  361. return;
  362. }
  363. else {
  364. Py_DECREF(n);
  365. Py_DECREF(v);
  366. }
  367. }
  368. args = string_intern(self, name);
  369. if (args == NULL) {
  370. Py_DECREF(container);
  371. return;
  372. }
  373. args = Py_BuildValue("(NN)", args, container);
  374. if (args == NULL) {
  375. return;
  376. }
  377. /* Container is now a borrowed reference; ignore it. */
  378. self->in_callback = 1;
  379. rv = call_with_frame("StartElement", __LINE__,
  380. self->handlers[StartElement], args, self);
  381. self->in_callback = 0;
  382. Py_DECREF(args);
  383. if (rv == NULL) {
  384. flag_error(self);
  385. return;
  386. }
  387. Py_DECREF(rv);
  388. }
  389. }
  390. #define RC_HANDLER(RC, NAME, PARAMS, INIT, PARAM_FORMAT, CONVERSION, \
  391. RETURN, GETUSERDATA) \
  392. static RC \
  393. my_##NAME##Handler PARAMS {\
  394. xmlparseobject *self = GETUSERDATA ; \
  395. PyObject *args = NULL; \
  396. PyObject *rv = NULL; \
  397. INIT \
  398. \
  399. if (have_handler(self, NAME)) { \
  400. if (PyErr_Occurred()) \
  401. return RETURN; \
  402. if (flush_character_buffer(self) < 0) \
  403. return RETURN; \
  404. args = Py_BuildValue PARAM_FORMAT ;\
  405. if (!args) { flag_error(self); return RETURN;} \
  406. self->in_callback = 1; \
  407. rv = call_with_frame(#NAME,__LINE__, \
  408. self->handlers[NAME], args, self); \
  409. self->in_callback = 0; \
  410. Py_DECREF(args); \
  411. if (rv == NULL) { \
  412. flag_error(self); \
  413. return RETURN; \
  414. } \
  415. CONVERSION \
  416. Py_DECREF(rv); \
  417. } \
  418. return RETURN; \
  419. }
  420. #define VOID_HANDLER(NAME, PARAMS, PARAM_FORMAT) \
  421. RC_HANDLER(void, NAME, PARAMS, ;, PARAM_FORMAT, ;, ;,\
  422. (xmlparseobject *)userData)
  423. #define INT_HANDLER(NAME, PARAMS, PARAM_FORMAT)\
  424. RC_HANDLER(int, NAME, PARAMS, int rc=0;, PARAM_FORMAT, \
  425. rc = PyLong_AsLong(rv);, rc, \
  426. (xmlparseobject *)userData)
  427. VOID_HANDLER(EndElement,
  428. (void *userData, const XML_Char *name),
  429. ("(N)", string_intern(self, name)))
  430. VOID_HANDLER(ProcessingInstruction,
  431. (void *userData,
  432. const XML_Char *target,
  433. const XML_Char *data),
  434. ("(NO&)", string_intern(self, target), conv_string_to_unicode ,data))
  435. VOID_HANDLER(UnparsedEntityDecl,
  436. (void *userData,
  437. const XML_Char *entityName,
  438. const XML_Char *base,
  439. const XML_Char *systemId,
  440. const XML_Char *publicId,
  441. const XML_Char *notationName),
  442. ("(NNNNN)",
  443. string_intern(self, entityName), string_intern(self, base),
  444. string_intern(self, systemId), string_intern(self, publicId),
  445. string_intern(self, notationName)))
  446. VOID_HANDLER(EntityDecl,
  447. (void *userData,
  448. const XML_Char *entityName,
  449. int is_parameter_entity,
  450. const XML_Char *value,
  451. int value_length,
  452. const XML_Char *base,
  453. const XML_Char *systemId,
  454. const XML_Char *publicId,
  455. const XML_Char *notationName),
  456. ("NiNNNNN",
  457. string_intern(self, entityName), is_parameter_entity,
  458. (conv_string_len_to_unicode(value, value_length)),
  459. string_intern(self, base), string_intern(self, systemId),
  460. string_intern(self, publicId),
  461. string_intern(self, notationName)))
  462. VOID_HANDLER(XmlDecl,
  463. (void *userData,
  464. const XML_Char *version,
  465. const XML_Char *encoding,
  466. int standalone),
  467. ("(O&O&i)",
  468. conv_string_to_unicode ,version, conv_string_to_unicode ,encoding,
  469. standalone))
  470. static PyObject *
  471. conv_content_model(XML_Content * const model,
  472. PyObject *(*conv_string)(const XML_Char *))
  473. {
  474. PyObject *result = NULL;
  475. PyObject *children = PyTuple_New(model->numchildren);
  476. int i;
  477. if (children != NULL) {
  478. assert(model->numchildren < INT_MAX);
  479. for (i = 0; i < (int)model->numchildren; ++i) {
  480. PyObject *child = conv_content_model(&model->children[i],
  481. conv_string);
  482. if (child == NULL) {
  483. Py_XDECREF(children);
  484. return NULL;
  485. }
  486. PyTuple_SET_ITEM(children, i, child);
  487. }
  488. result = Py_BuildValue("(iiO&N)",
  489. model->type, model->quant,
  490. conv_string,model->name, children);
  491. }
  492. return result;
  493. }
  494. static void
  495. my_ElementDeclHandler(void *userData,
  496. const XML_Char *name,
  497. XML_Content *model)
  498. {
  499. xmlparseobject *self = (xmlparseobject *)userData;
  500. PyObject *args = NULL;
  501. if (have_handler(self, ElementDecl)) {
  502. PyObject *rv = NULL;
  503. PyObject *modelobj, *nameobj;
  504. if (PyErr_Occurred())
  505. return;
  506. if (flush_character_buffer(self) < 0)
  507. goto finally;
  508. modelobj = conv_content_model(model, (conv_string_to_unicode));
  509. if (modelobj == NULL) {
  510. flag_error(self);
  511. goto finally;
  512. }
  513. nameobj = string_intern(self, name);
  514. if (nameobj == NULL) {
  515. Py_DECREF(modelobj);
  516. flag_error(self);
  517. goto finally;
  518. }
  519. args = Py_BuildValue("NN", nameobj, modelobj);
  520. if (args == NULL) {
  521. flag_error(self);
  522. goto finally;
  523. }
  524. self->in_callback = 1;
  525. rv = call_with_frame("ElementDecl", __LINE__,
  526. self->handlers[ElementDecl], args, self);
  527. self->in_callback = 0;
  528. if (rv == NULL) {
  529. flag_error(self);
  530. goto finally;
  531. }
  532. Py_DECREF(rv);
  533. }
  534. finally:
  535. Py_XDECREF(args);
  536. XML_FreeContentModel(self->itself, model);
  537. return;
  538. }
  539. VOID_HANDLER(AttlistDecl,
  540. (void *userData,
  541. const XML_Char *elname,
  542. const XML_Char *attname,
  543. const XML_Char *att_type,
  544. const XML_Char *dflt,
  545. int isrequired),
  546. ("(NNO&O&i)",
  547. string_intern(self, elname), string_intern(self, attname),
  548. conv_string_to_unicode ,att_type, conv_string_to_unicode ,dflt,
  549. isrequired))
  550. #if XML_COMBINED_VERSION >= 19504
  551. VOID_HANDLER(SkippedEntity,
  552. (void *userData,
  553. const XML_Char *entityName,
  554. int is_parameter_entity),
  555. ("Ni",
  556. string_intern(self, entityName), is_parameter_entity))
  557. #endif
  558. VOID_HANDLER(NotationDecl,
  559. (void *userData,
  560. const XML_Char *notationName,
  561. const XML_Char *base,
  562. const XML_Char *systemId,
  563. const XML_Char *publicId),
  564. ("(NNNN)",
  565. string_intern(self, notationName), string_intern(self, base),
  566. string_intern(self, systemId), string_intern(self, publicId)))
  567. VOID_HANDLER(StartNamespaceDecl,
  568. (void *userData,
  569. const XML_Char *prefix,
  570. const XML_Char *uri),
  571. ("(NN)",
  572. string_intern(self, prefix), string_intern(self, uri)))
  573. VOID_HANDLER(EndNamespaceDecl,
  574. (void *userData,
  575. const XML_Char *prefix),
  576. ("(N)", string_intern(self, prefix)))
  577. VOID_HANDLER(Comment,
  578. (void *userData, const XML_Char *data),
  579. ("(O&)", conv_string_to_unicode ,data))
  580. VOID_HANDLER(StartCdataSection,
  581. (void *userData),
  582. ("()"))
  583. VOID_HANDLER(EndCdataSection,
  584. (void *userData),
  585. ("()"))
  586. VOID_HANDLER(Default,
  587. (void *userData, const XML_Char *s, int len),
  588. ("(N)", (conv_string_len_to_unicode(s,len))))
  589. VOID_HANDLER(DefaultHandlerExpand,
  590. (void *userData, const XML_Char *s, int len),
  591. ("(N)", (conv_string_len_to_unicode(s,len))))
  592. #define my_DefaultHandlerExpand my_DefaultHandlerExpandHandler
  593. INT_HANDLER(NotStandalone,
  594. (void *userData),
  595. ("()"))
  596. RC_HANDLER(int, ExternalEntityRef,
  597. (XML_Parser parser,
  598. const XML_Char *context,
  599. const XML_Char *base,
  600. const XML_Char *systemId,
  601. const XML_Char *publicId),
  602. int rc=0;,
  603. ("(O&NNN)",
  604. conv_string_to_unicode ,context, string_intern(self, base),
  605. string_intern(self, systemId), string_intern(self, publicId)),
  606. rc = PyLong_AsLong(rv);, rc,
  607. XML_GetUserData(parser))
  608. /* XXX UnknownEncodingHandler */
  609. VOID_HANDLER(StartDoctypeDecl,
  610. (void *userData, const XML_Char *doctypeName,
  611. const XML_Char *sysid, const XML_Char *pubid,
  612. int has_internal_subset),
  613. ("(NNNi)", string_intern(self, doctypeName),
  614. string_intern(self, sysid), string_intern(self, pubid),
  615. has_internal_subset))
  616. VOID_HANDLER(EndDoctypeDecl, (void *userData), ("()"))
  617. /* ---------------------------------------------------------------- */
  618. /*[clinic input]
  619. class pyexpat.xmlparser "xmlparseobject *" "&Xmlparsetype"
  620. [clinic start generated code]*/
  621. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=2393162385232e1c]*/
  622. static PyObject *
  623. get_parse_result(pyexpat_state *state, xmlparseobject *self, int rv)
  624. {
  625. if (PyErr_Occurred()) {
  626. return NULL;
  627. }
  628. if (rv == 0) {
  629. return set_error(state, self, XML_GetErrorCode(self->itself));
  630. }
  631. if (flush_character_buffer(self) < 0) {
  632. return NULL;
  633. }
  634. return PyLong_FromLong(rv);
  635. }
  636. #define MAX_CHUNK_SIZE (1 << 20)
  637. /*[clinic input]
  638. pyexpat.xmlparser.SetReparseDeferralEnabled
  639. enabled: bool
  640. /
  641. Enable/Disable reparse deferral; enabled by default with Expat >=2.6.0.
  642. [clinic start generated code]*/
  643. static PyObject *
  644. pyexpat_xmlparser_SetReparseDeferralEnabled_impl(xmlparseobject *self,
  645. int enabled)
  646. /*[clinic end generated code: output=5ec539e3b63c8c49 input=021eb9e0bafc32c5]*/
  647. {
  648. #if XML_COMBINED_VERSION >= 20600
  649. XML_SetReparseDeferralEnabled(self->itself, enabled ? XML_TRUE : XML_FALSE);
  650. self->reparse_deferral_enabled = (bool)enabled;
  651. #endif
  652. Py_RETURN_NONE;
  653. }
  654. /*[clinic input]
  655. pyexpat.xmlparser.GetReparseDeferralEnabled
  656. Retrieve reparse deferral enabled status; always returns false with Expat <2.6.0.
  657. [clinic start generated code]*/
  658. static PyObject *
  659. pyexpat_xmlparser_GetReparseDeferralEnabled_impl(xmlparseobject *self)
  660. /*[clinic end generated code: output=4e91312e88a595a8 input=54b5f11d32b20f3e]*/
  661. {
  662. return PyBool_FromLong(self->reparse_deferral_enabled);
  663. }
  664. /*[clinic input]
  665. pyexpat.xmlparser.Parse
  666. cls: defining_class
  667. data: object
  668. isfinal: bool = False
  669. /
  670. Parse XML data.
  671. `isfinal' should be true at end of input.
  672. [clinic start generated code]*/
  673. static PyObject *
  674. pyexpat_xmlparser_Parse_impl(xmlparseobject *self, PyTypeObject *cls,
  675. PyObject *data, int isfinal)
  676. /*[clinic end generated code: output=8faffe07fe1f862a input=d0eb2a69fab3b9f1]*/
  677. {
  678. const char *s;
  679. Py_ssize_t slen;
  680. Py_buffer view;
  681. int rc;
  682. pyexpat_state *state = PyType_GetModuleState(cls);
  683. if (PyUnicode_Check(data)) {
  684. view.buf = NULL;
  685. s = PyUnicode_AsUTF8AndSize(data, &slen);
  686. if (s == NULL)
  687. return NULL;
  688. /* Explicitly set UTF-8 encoding. Return code ignored. */
  689. (void)XML_SetEncoding(self->itself, "utf-8");
  690. }
  691. else {
  692. if (PyObject_GetBuffer(data, &view, PyBUF_SIMPLE) < 0)
  693. return NULL;
  694. s = view.buf;
  695. slen = view.len;
  696. }
  697. static_assert(MAX_CHUNK_SIZE <= INT_MAX,
  698. "MAX_CHUNK_SIZE is larger than INT_MAX");
  699. while (slen > MAX_CHUNK_SIZE) {
  700. rc = XML_Parse(self->itself, s, MAX_CHUNK_SIZE, 0);
  701. if (!rc)
  702. goto done;
  703. s += MAX_CHUNK_SIZE;
  704. slen -= MAX_CHUNK_SIZE;
  705. }
  706. assert(slen <= INT_MAX);
  707. rc = XML_Parse(self->itself, s, (int)slen, isfinal);
  708. done:
  709. if (view.buf != NULL) {
  710. PyBuffer_Release(&view);
  711. }
  712. return get_parse_result(state, self, rc);
  713. }
  714. /* File reading copied from cPickle */
  715. #define BUF_SIZE 2048
  716. static int
  717. readinst(char *buf, int buf_size, PyObject *meth)
  718. {
  719. PyObject *str;
  720. Py_ssize_t len;
  721. const char *ptr;
  722. str = PyObject_CallFunction(meth, "i", buf_size);
  723. if (str == NULL)
  724. goto error;
  725. if (PyBytes_Check(str))
  726. ptr = PyBytes_AS_STRING(str);
  727. else if (PyByteArray_Check(str))
  728. ptr = PyByteArray_AS_STRING(str);
  729. else {
  730. PyErr_Format(PyExc_TypeError,
  731. "read() did not return a bytes object (type=%.400s)",
  732. Py_TYPE(str)->tp_name);
  733. goto error;
  734. }
  735. len = Py_SIZE(str);
  736. if (len > buf_size) {
  737. PyErr_Format(PyExc_ValueError,
  738. "read() returned too much data: "
  739. "%i bytes requested, %zd returned",
  740. buf_size, len);
  741. goto error;
  742. }
  743. memcpy(buf, ptr, len);
  744. Py_DECREF(str);
  745. /* len <= buf_size <= INT_MAX */
  746. return (int)len;
  747. error:
  748. Py_XDECREF(str);
  749. return -1;
  750. }
  751. /*[clinic input]
  752. pyexpat.xmlparser.ParseFile
  753. cls: defining_class
  754. file: object
  755. /
  756. Parse XML data from file-like object.
  757. [clinic start generated code]*/
  758. static PyObject *
  759. pyexpat_xmlparser_ParseFile_impl(xmlparseobject *self, PyTypeObject *cls,
  760. PyObject *file)
  761. /*[clinic end generated code: output=34780a094c8ca3ae input=ba4bc9c541684793]*/
  762. {
  763. int rv = 1;
  764. PyObject *readmethod = NULL;
  765. pyexpat_state *state = PyType_GetModuleState(cls);
  766. if (_PyObject_LookupAttr(file, state->str_read, &readmethod) < 0) {
  767. return NULL;
  768. }
  769. if (readmethod == NULL) {
  770. PyErr_SetString(PyExc_TypeError,
  771. "argument must have 'read' attribute");
  772. return NULL;
  773. }
  774. for (;;) {
  775. int bytes_read;
  776. void *buf = XML_GetBuffer(self->itself, BUF_SIZE);
  777. if (buf == NULL) {
  778. Py_XDECREF(readmethod);
  779. return get_parse_result(state, self, 0);
  780. }
  781. bytes_read = readinst(buf, BUF_SIZE, readmethod);
  782. if (bytes_read < 0) {
  783. Py_DECREF(readmethod);
  784. return NULL;
  785. }
  786. rv = XML_ParseBuffer(self->itself, bytes_read, bytes_read == 0);
  787. if (PyErr_Occurred()) {
  788. Py_XDECREF(readmethod);
  789. return NULL;
  790. }
  791. if (!rv || bytes_read == 0)
  792. break;
  793. }
  794. Py_XDECREF(readmethod);
  795. return get_parse_result(state, self, rv);
  796. }
  797. /*[clinic input]
  798. pyexpat.xmlparser.SetBase
  799. base: str
  800. /
  801. Set the base URL for the parser.
  802. [clinic start generated code]*/
  803. static PyObject *
  804. pyexpat_xmlparser_SetBase_impl(xmlparseobject *self, const char *base)
  805. /*[clinic end generated code: output=c212ddceb607b539 input=c684e5de895ee1a8]*/
  806. {
  807. if (!XML_SetBase(self->itself, base)) {
  808. return PyErr_NoMemory();
  809. }
  810. Py_RETURN_NONE;
  811. }
  812. /*[clinic input]
  813. pyexpat.xmlparser.GetBase
  814. Return base URL string for the parser.
  815. [clinic start generated code]*/
  816. static PyObject *
  817. pyexpat_xmlparser_GetBase_impl(xmlparseobject *self)
  818. /*[clinic end generated code: output=2886cb21f9a8739a input=918d71c38009620e]*/
  819. {
  820. return Py_BuildValue("z", XML_GetBase(self->itself));
  821. }
  822. /*[clinic input]
  823. pyexpat.xmlparser.GetInputContext
  824. Return the untranslated text of the input that caused the current event.
  825. If the event was generated by a large amount of text (such as a start tag
  826. for an element with many attributes), not all of the text may be available.
  827. [clinic start generated code]*/
  828. static PyObject *
  829. pyexpat_xmlparser_GetInputContext_impl(xmlparseobject *self)
  830. /*[clinic end generated code: output=a88026d683fc22cc input=034df8712db68379]*/
  831. {
  832. if (self->in_callback) {
  833. int offset, size;
  834. const char *buffer
  835. = XML_GetInputContext(self->itself, &offset, &size);
  836. if (buffer != NULL)
  837. return PyBytes_FromStringAndSize(buffer + offset,
  838. size - offset);
  839. else
  840. Py_RETURN_NONE;
  841. }
  842. else
  843. Py_RETURN_NONE;
  844. }
  845. /*[clinic input]
  846. pyexpat.xmlparser.ExternalEntityParserCreate
  847. cls: defining_class
  848. context: str(accept={str, NoneType})
  849. encoding: str = NULL
  850. /
  851. Create a parser for parsing an external entity based on the information passed to the ExternalEntityRefHandler.
  852. [clinic start generated code]*/
  853. static PyObject *
  854. pyexpat_xmlparser_ExternalEntityParserCreate_impl(xmlparseobject *self,
  855. PyTypeObject *cls,
  856. const char *context,
  857. const char *encoding)
  858. /*[clinic end generated code: output=01d4472b49cb3f92 input=ec70c6b9e6e9619a]*/
  859. {
  860. xmlparseobject *new_parser;
  861. int i;
  862. pyexpat_state *state = PyType_GetModuleState(cls);
  863. new_parser = PyObject_GC_New(xmlparseobject, state->xml_parse_type);
  864. if (new_parser == NULL) {
  865. return NULL;
  866. }
  867. new_parser->buffer_size = self->buffer_size;
  868. new_parser->buffer_used = 0;
  869. new_parser->buffer = NULL;
  870. new_parser->ordered_attributes = self->ordered_attributes;
  871. new_parser->specified_attributes = self->specified_attributes;
  872. new_parser->in_callback = 0;
  873. new_parser->ns_prefixes = self->ns_prefixes;
  874. new_parser->itself = XML_ExternalEntityParserCreate(self->itself, context,
  875. encoding);
  876. new_parser->handlers = 0;
  877. new_parser->intern = Py_XNewRef(self->intern);
  878. if (self->buffer != NULL) {
  879. new_parser->buffer = PyMem_Malloc(new_parser->buffer_size);
  880. if (new_parser->buffer == NULL) {
  881. Py_DECREF(new_parser);
  882. return PyErr_NoMemory();
  883. }
  884. }
  885. if (!new_parser->itself) {
  886. Py_DECREF(new_parser);
  887. return PyErr_NoMemory();
  888. }
  889. XML_SetUserData(new_parser->itself, (void *)new_parser);
  890. /* allocate and clear handlers first */
  891. for (i = 0; handler_info[i].name != NULL; i++)
  892. /* do nothing */;
  893. new_parser->handlers = PyMem_New(PyObject *, i);
  894. if (!new_parser->handlers) {
  895. Py_DECREF(new_parser);
  896. return PyErr_NoMemory();
  897. }
  898. clear_handlers(new_parser, 1);
  899. /* then copy handlers from self */
  900. for (i = 0; handler_info[i].name != NULL; i++) {
  901. PyObject *handler = self->handlers[i];
  902. if (handler != NULL) {
  903. new_parser->handlers[i] = Py_NewRef(handler);
  904. handler_info[i].setter(new_parser->itself,
  905. handler_info[i].handler);
  906. }
  907. }
  908. PyObject_GC_Track(new_parser);
  909. return (PyObject *)new_parser;
  910. }
  911. /*[clinic input]
  912. pyexpat.xmlparser.SetParamEntityParsing
  913. flag: int
  914. /
  915. Controls parsing of parameter entities (including the external DTD subset).
  916. Possible flag values are XML_PARAM_ENTITY_PARSING_NEVER,
  917. XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE and
  918. XML_PARAM_ENTITY_PARSING_ALWAYS. Returns true if setting the flag
  919. was successful.
  920. [clinic start generated code]*/
  921. static PyObject *
  922. pyexpat_xmlparser_SetParamEntityParsing_impl(xmlparseobject *self, int flag)
  923. /*[clinic end generated code: output=18668ee8e760d64c input=8aea19b4b15e9af1]*/
  924. {
  925. flag = XML_SetParamEntityParsing(self->itself, flag);
  926. return PyLong_FromLong(flag);
  927. }
  928. #if XML_COMBINED_VERSION >= 19505
  929. /*[clinic input]
  930. pyexpat.xmlparser.UseForeignDTD
  931. cls: defining_class
  932. flag: bool = True
  933. /
  934. Allows the application to provide an artificial external subset if one is not specified as part of the document instance.
  935. This readily allows the use of a 'default' document type controlled by the
  936. application, while still getting the advantage of providing document type
  937. information to the parser. 'flag' defaults to True if not provided.
  938. [clinic start generated code]*/
  939. static PyObject *
  940. pyexpat_xmlparser_UseForeignDTD_impl(xmlparseobject *self, PyTypeObject *cls,
  941. int flag)
  942. /*[clinic end generated code: output=d7d98252bd25a20f input=23440ecb0573fb29]*/
  943. {
  944. pyexpat_state *state = PyType_GetModuleState(cls);
  945. enum XML_Error rc;
  946. rc = XML_UseForeignDTD(self->itself, flag ? XML_TRUE : XML_FALSE);
  947. if (rc != XML_ERROR_NONE) {
  948. return set_error(state, self, rc);
  949. }
  950. Py_RETURN_NONE;
  951. }
  952. #endif
  953. static struct PyMethodDef xmlparse_methods[] = {
  954. PYEXPAT_XMLPARSER_PARSE_METHODDEF
  955. PYEXPAT_XMLPARSER_PARSEFILE_METHODDEF
  956. PYEXPAT_XMLPARSER_SETBASE_METHODDEF
  957. PYEXPAT_XMLPARSER_GETBASE_METHODDEF
  958. PYEXPAT_XMLPARSER_GETINPUTCONTEXT_METHODDEF
  959. PYEXPAT_XMLPARSER_EXTERNALENTITYPARSERCREATE_METHODDEF
  960. PYEXPAT_XMLPARSER_SETPARAMENTITYPARSING_METHODDEF
  961. #if XML_COMBINED_VERSION >= 19505
  962. PYEXPAT_XMLPARSER_USEFOREIGNDTD_METHODDEF
  963. #endif
  964. PYEXPAT_XMLPARSER_SETREPARSEDEFERRALENABLED_METHODDEF
  965. PYEXPAT_XMLPARSER_GETREPARSEDEFERRALENABLED_METHODDEF
  966. {NULL, NULL} /* sentinel */
  967. };
  968. /* ---------- */
  969. /* pyexpat international encoding support.
  970. Make it as simple as possible.
  971. */
  972. static const unsigned char template_buffer[256] =
  973. {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
  974. 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
  975. 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
  976. 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
  977. 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91,
  978. 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107,
  979. 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122,
  980. 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137,
  981. 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152,
  982. 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167,
  983. 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182,
  984. 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197,
  985. 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212,
  986. 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227,
  987. 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242,
  988. 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255};
  989. static int
  990. PyUnknownEncodingHandler(void *encodingHandlerData,
  991. const XML_Char *name,
  992. XML_Encoding *info)
  993. {
  994. PyObject *u;
  995. int i;
  996. const void *data;
  997. int kind;
  998. if (PyErr_Occurred())
  999. return XML_STATUS_ERROR;
  1000. u = PyUnicode_Decode((const char*) template_buffer, 256, name, "replace");
  1001. if (u == NULL || PyUnicode_READY(u)) {
  1002. Py_XDECREF(u);
  1003. return XML_STATUS_ERROR;
  1004. }
  1005. if (PyUnicode_GET_LENGTH(u) != 256) {
  1006. Py_DECREF(u);
  1007. PyErr_SetString(PyExc_ValueError,
  1008. "multi-byte encodings are not supported");
  1009. return XML_STATUS_ERROR;
  1010. }
  1011. kind = PyUnicode_KIND(u);
  1012. data = PyUnicode_DATA(u);
  1013. for (i = 0; i < 256; i++) {
  1014. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  1015. if (ch != Py_UNICODE_REPLACEMENT_CHARACTER)
  1016. info->map[i] = ch;
  1017. else
  1018. info->map[i] = -1;
  1019. }
  1020. info->data = NULL;
  1021. info->convert = NULL;
  1022. info->release = NULL;
  1023. Py_DECREF(u);
  1024. return XML_STATUS_OK;
  1025. }
  1026. static PyObject *
  1027. newxmlparseobject(pyexpat_state *state, const char *encoding,
  1028. const char *namespace_separator, PyObject *intern)
  1029. {
  1030. int i;
  1031. xmlparseobject *self;
  1032. self = PyObject_GC_New(xmlparseobject, state->xml_parse_type);
  1033. if (self == NULL)
  1034. return NULL;
  1035. self->buffer = NULL;
  1036. self->buffer_size = CHARACTER_DATA_BUFFER_SIZE;
  1037. self->buffer_used = 0;
  1038. self->ordered_attributes = 0;
  1039. self->specified_attributes = 0;
  1040. self->in_callback = 0;
  1041. self->ns_prefixes = 0;
  1042. self->handlers = NULL;
  1043. self->intern = Py_XNewRef(intern);
  1044. #if XML_COMBINED_VERSION >= 20600
  1045. self->reparse_deferral_enabled = true;
  1046. #else
  1047. self->reparse_deferral_enabled = false;
  1048. #endif
  1049. /* namespace_separator is either NULL or contains one char + \0 */
  1050. self->itself = XML_ParserCreate_MM(encoding, &ExpatMemoryHandler,
  1051. namespace_separator);
  1052. if (self->itself == NULL) {
  1053. PyErr_SetString(PyExc_RuntimeError,
  1054. "XML_ParserCreate failed");
  1055. Py_DECREF(self);
  1056. return NULL;
  1057. }
  1058. #if XML_COMBINED_VERSION >= 20100
  1059. /* This feature was added upstream in libexpat 2.1.0. */
  1060. XML_SetHashSalt(self->itself,
  1061. (unsigned long)_Py_HashSecret.expat.hashsalt);
  1062. #endif
  1063. XML_SetUserData(self->itself, (void *)self);
  1064. XML_SetUnknownEncodingHandler(self->itself,
  1065. (XML_UnknownEncodingHandler) PyUnknownEncodingHandler, NULL);
  1066. for (i = 0; handler_info[i].name != NULL; i++)
  1067. /* do nothing */;
  1068. self->handlers = PyMem_New(PyObject *, i);
  1069. if (!self->handlers) {
  1070. Py_DECREF(self);
  1071. return PyErr_NoMemory();
  1072. }
  1073. clear_handlers(self, 1);
  1074. PyObject_GC_Track(self);
  1075. return (PyObject*)self;
  1076. }
  1077. static int
  1078. xmlparse_traverse(xmlparseobject *op, visitproc visit, void *arg)
  1079. {
  1080. for (int i = 0; handler_info[i].name != NULL; i++) {
  1081. Py_VISIT(op->handlers[i]);
  1082. }
  1083. Py_VISIT(Py_TYPE(op));
  1084. return 0;
  1085. }
  1086. static int
  1087. xmlparse_clear(xmlparseobject *op)
  1088. {
  1089. clear_handlers(op, 0);
  1090. Py_CLEAR(op->intern);
  1091. return 0;
  1092. }
  1093. static void
  1094. xmlparse_dealloc(xmlparseobject *self)
  1095. {
  1096. PyObject_GC_UnTrack(self);
  1097. (void)xmlparse_clear(self);
  1098. if (self->itself != NULL)
  1099. XML_ParserFree(self->itself);
  1100. self->itself = NULL;
  1101. if (self->handlers != NULL) {
  1102. PyMem_Free(self->handlers);
  1103. self->handlers = NULL;
  1104. }
  1105. if (self->buffer != NULL) {
  1106. PyMem_Free(self->buffer);
  1107. self->buffer = NULL;
  1108. }
  1109. PyTypeObject *tp = Py_TYPE(self);
  1110. PyObject_GC_Del(self);
  1111. Py_DECREF(tp);
  1112. }
  1113. static PyObject *
  1114. xmlparse_handler_getter(xmlparseobject *self, struct HandlerInfo *hi)
  1115. {
  1116. assert((hi - handler_info) < (Py_ssize_t)Py_ARRAY_LENGTH(handler_info));
  1117. int handlernum = (int)(hi - handler_info);
  1118. PyObject *result = self->handlers[handlernum];
  1119. if (result == NULL)
  1120. result = Py_None;
  1121. return Py_NewRef(result);
  1122. }
  1123. static int
  1124. xmlparse_handler_setter(xmlparseobject *self, PyObject *v, struct HandlerInfo *hi)
  1125. {
  1126. assert((hi - handler_info) < (Py_ssize_t)Py_ARRAY_LENGTH(handler_info));
  1127. int handlernum = (int)(hi - handler_info);
  1128. if (v == NULL) {
  1129. PyErr_SetString(PyExc_RuntimeError, "Cannot delete attribute");
  1130. return -1;
  1131. }
  1132. if (handlernum == CharacterData) {
  1133. /* If we're changing the character data handler, flush all
  1134. * cached data with the old handler. Not sure there's a
  1135. * "right" thing to do, though, but this probably won't
  1136. * happen.
  1137. */
  1138. if (flush_character_buffer(self) < 0)
  1139. return -1;
  1140. }
  1141. xmlhandler c_handler = NULL;
  1142. if (v == Py_None) {
  1143. /* If this is the character data handler, and a character
  1144. data handler is already active, we need to be more
  1145. careful. What we can safely do is replace the existing
  1146. character data handler callback function with a no-op
  1147. function that will refuse to call Python. The downside
  1148. is that this doesn't completely remove the character
  1149. data handler from the C layer if there's any callback
  1150. active, so Expat does a little more work than it
  1151. otherwise would, but that's really an odd case. A more
  1152. elaborate system of handlers and state could remove the
  1153. C handler more effectively. */
  1154. if (handlernum == CharacterData && self->in_callback)
  1155. c_handler = noop_character_data_handler;
  1156. v = NULL;
  1157. }
  1158. else if (v != NULL) {
  1159. Py_INCREF(v);
  1160. c_handler = handler_info[handlernum].handler;
  1161. }
  1162. Py_XSETREF(self->handlers[handlernum], v);
  1163. handler_info[handlernum].setter(self->itself, c_handler);
  1164. return 0;
  1165. }
  1166. #define INT_GETTER(name) \
  1167. static PyObject * \
  1168. xmlparse_##name##_getter(xmlparseobject *self, void *closure) \
  1169. { \
  1170. return PyLong_FromLong((long) XML_Get##name(self->itself)); \
  1171. }
  1172. INT_GETTER(ErrorCode)
  1173. INT_GETTER(ErrorLineNumber)
  1174. INT_GETTER(ErrorColumnNumber)
  1175. INT_GETTER(ErrorByteIndex)
  1176. INT_GETTER(CurrentLineNumber)
  1177. INT_GETTER(CurrentColumnNumber)
  1178. INT_GETTER(CurrentByteIndex)
  1179. #undef INT_GETTER
  1180. static PyObject *
  1181. xmlparse_buffer_text_getter(xmlparseobject *self, void *closure)
  1182. {
  1183. return PyBool_FromLong(self->buffer != NULL);
  1184. }
  1185. static int
  1186. xmlparse_buffer_text_setter(xmlparseobject *self, PyObject *v, void *closure)
  1187. {
  1188. if (v == NULL) {
  1189. PyErr_SetString(PyExc_RuntimeError, "Cannot delete attribute");
  1190. return -1;
  1191. }
  1192. int b = PyObject_IsTrue(v);
  1193. if (b < 0)
  1194. return -1;
  1195. if (b) {
  1196. if (self->buffer == NULL) {
  1197. self->buffer = PyMem_Malloc(self->buffer_size);
  1198. if (self->buffer == NULL) {
  1199. PyErr_NoMemory();
  1200. return -1;
  1201. }
  1202. self->buffer_used = 0;
  1203. }
  1204. }
  1205. else if (self->buffer != NULL) {
  1206. if (flush_character_buffer(self) < 0)
  1207. return -1;
  1208. PyMem_Free(self->buffer);
  1209. self->buffer = NULL;
  1210. }
  1211. return 0;
  1212. }
  1213. static PyObject *
  1214. xmlparse_buffer_size_getter(xmlparseobject *self, void *closure)
  1215. {
  1216. return PyLong_FromLong((long) self->buffer_size);
  1217. }
  1218. static int
  1219. xmlparse_buffer_size_setter(xmlparseobject *self, PyObject *v, void *closure)
  1220. {
  1221. if (v == NULL) {
  1222. PyErr_SetString(PyExc_RuntimeError, "Cannot delete attribute");
  1223. return -1;
  1224. }
  1225. long new_buffer_size;
  1226. if (!PyLong_Check(v)) {
  1227. PyErr_SetString(PyExc_TypeError, "buffer_size must be an integer");
  1228. return -1;
  1229. }
  1230. new_buffer_size = PyLong_AsLong(v);
  1231. if (new_buffer_size <= 0) {
  1232. if (!PyErr_Occurred())
  1233. PyErr_SetString(PyExc_ValueError, "buffer_size must be greater than zero");
  1234. return -1;
  1235. }
  1236. /* trivial case -- no change */
  1237. if (new_buffer_size == self->buffer_size) {
  1238. return 0;
  1239. }
  1240. /* check maximum */
  1241. if (new_buffer_size > INT_MAX) {
  1242. PyErr_Format(PyExc_ValueError, "buffer_size must not be greater than %i", INT_MAX);
  1243. return -1;
  1244. }
  1245. if (self->buffer != NULL) {
  1246. /* there is already a buffer */
  1247. if (self->buffer_used != 0) {
  1248. if (flush_character_buffer(self) < 0) {
  1249. return -1;
  1250. }
  1251. }
  1252. /* free existing buffer */
  1253. PyMem_Free(self->buffer);
  1254. }
  1255. self->buffer = PyMem_Malloc(new_buffer_size);
  1256. if (self->buffer == NULL) {
  1257. PyErr_NoMemory();
  1258. return -1;
  1259. }
  1260. self->buffer_size = new_buffer_size;
  1261. return 0;
  1262. }
  1263. static PyObject *
  1264. xmlparse_buffer_used_getter(xmlparseobject *self, void *closure)
  1265. {
  1266. return PyLong_FromLong((long) self->buffer_used);
  1267. }
  1268. static PyObject *
  1269. xmlparse_namespace_prefixes_getter(xmlparseobject *self, void *closure)
  1270. {
  1271. return PyBool_FromLong(self->ns_prefixes);
  1272. }
  1273. static int
  1274. xmlparse_namespace_prefixes_setter(xmlparseobject *self, PyObject *v, void *closure)
  1275. {
  1276. if (v == NULL) {
  1277. PyErr_SetString(PyExc_RuntimeError, "Cannot delete attribute");
  1278. return -1;
  1279. }
  1280. int b = PyObject_IsTrue(v);
  1281. if (b < 0)
  1282. return -1;
  1283. self->ns_prefixes = b;
  1284. XML_SetReturnNSTriplet(self->itself, self->ns_prefixes);
  1285. return 0;
  1286. }
  1287. static PyObject *
  1288. xmlparse_ordered_attributes_getter(xmlparseobject *self, void *closure)
  1289. {
  1290. return PyBool_FromLong(self->ordered_attributes);
  1291. }
  1292. static int
  1293. xmlparse_ordered_attributes_setter(xmlparseobject *self, PyObject *v, void *closure)
  1294. {
  1295. if (v == NULL) {
  1296. PyErr_SetString(PyExc_RuntimeError, "Cannot delete attribute");
  1297. return -1;
  1298. }
  1299. int b = PyObject_IsTrue(v);
  1300. if (b < 0)
  1301. return -1;
  1302. self->ordered_attributes = b;
  1303. return 0;
  1304. }
  1305. static PyObject *
  1306. xmlparse_specified_attributes_getter(xmlparseobject *self, void *closure)
  1307. {
  1308. return PyBool_FromLong((long) self->specified_attributes);
  1309. }
  1310. static int
  1311. xmlparse_specified_attributes_setter(xmlparseobject *self, PyObject *v, void *closure)
  1312. {
  1313. if (v == NULL) {
  1314. PyErr_SetString(PyExc_RuntimeError, "Cannot delete attribute");
  1315. return -1;
  1316. }
  1317. int b = PyObject_IsTrue(v);
  1318. if (b < 0)
  1319. return -1;
  1320. self->specified_attributes = b;
  1321. return 0;
  1322. }
  1323. static PyMemberDef xmlparse_members[] = {
  1324. {"intern", T_OBJECT, offsetof(xmlparseobject, intern), READONLY, NULL},
  1325. {NULL}
  1326. };
  1327. #define XMLPARSE_GETTER_DEF(name) \
  1328. {#name, (getter)xmlparse_##name##_getter, NULL, NULL},
  1329. #define XMLPARSE_GETTER_SETTER_DEF(name) \
  1330. {#name, (getter)xmlparse_##name##_getter, \
  1331. (setter)xmlparse_##name##_setter, NULL},
  1332. static PyGetSetDef xmlparse_getsetlist[] = {
  1333. XMLPARSE_GETTER_DEF(ErrorCode)
  1334. XMLPARSE_GETTER_DEF(ErrorLineNumber)
  1335. XMLPARSE_GETTER_DEF(ErrorColumnNumber)
  1336. XMLPARSE_GETTER_DEF(ErrorByteIndex)
  1337. XMLPARSE_GETTER_DEF(CurrentLineNumber)
  1338. XMLPARSE_GETTER_DEF(CurrentColumnNumber)
  1339. XMLPARSE_GETTER_DEF(CurrentByteIndex)
  1340. XMLPARSE_GETTER_SETTER_DEF(buffer_size)
  1341. XMLPARSE_GETTER_SETTER_DEF(buffer_text)
  1342. XMLPARSE_GETTER_DEF(buffer_used)
  1343. XMLPARSE_GETTER_SETTER_DEF(namespace_prefixes)
  1344. XMLPARSE_GETTER_SETTER_DEF(ordered_attributes)
  1345. XMLPARSE_GETTER_SETTER_DEF(specified_attributes)
  1346. {NULL},
  1347. };
  1348. #undef XMLPARSE_GETTER_DEF
  1349. #undef XMLPARSE_GETTER_SETTER_DEF
  1350. PyDoc_STRVAR(Xmlparsetype__doc__, "XML parser");
  1351. static PyType_Slot _xml_parse_type_spec_slots[] = {
  1352. {Py_tp_dealloc, xmlparse_dealloc},
  1353. {Py_tp_doc, (void *)Xmlparsetype__doc__},
  1354. {Py_tp_traverse, xmlparse_traverse},
  1355. {Py_tp_clear, xmlparse_clear},
  1356. {Py_tp_methods, xmlparse_methods},
  1357. {Py_tp_members, xmlparse_members},
  1358. {Py_tp_getset, xmlparse_getsetlist},
  1359. {0, 0}
  1360. };
  1361. static PyType_Spec _xml_parse_type_spec = {
  1362. .name = "pyexpat.xmlparser",
  1363. .basicsize = sizeof(xmlparseobject),
  1364. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  1365. Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_IMMUTABLETYPE),
  1366. .slots = _xml_parse_type_spec_slots,
  1367. };
  1368. /* End of code for xmlparser objects */
  1369. /* -------------------------------------------------------- */
  1370. /*[clinic input]
  1371. pyexpat.ParserCreate
  1372. encoding: str(accept={str, NoneType}) = None
  1373. namespace_separator: str(accept={str, NoneType}) = None
  1374. intern: object = NULL
  1375. Return a new XML parser object.
  1376. [clinic start generated code]*/
  1377. static PyObject *
  1378. pyexpat_ParserCreate_impl(PyObject *module, const char *encoding,
  1379. const char *namespace_separator, PyObject *intern)
  1380. /*[clinic end generated code: output=295c0cf01ab1146c input=e8da8e8d7122cb5d]*/
  1381. {
  1382. PyObject *result;
  1383. int intern_decref = 0;
  1384. if (namespace_separator != NULL
  1385. && strlen(namespace_separator) > 1) {
  1386. PyErr_SetString(PyExc_ValueError,
  1387. "namespace_separator must be at most one"
  1388. " character, omitted, or None");
  1389. return NULL;
  1390. }
  1391. /* Explicitly passing None means no interning is desired.
  1392. Not passing anything means that a new dictionary is used. */
  1393. if (intern == Py_None)
  1394. intern = NULL;
  1395. else if (intern == NULL) {
  1396. intern = PyDict_New();
  1397. if (!intern)
  1398. return NULL;
  1399. intern_decref = 1;
  1400. }
  1401. else if (!PyDict_Check(intern)) {
  1402. PyErr_SetString(PyExc_TypeError, "intern must be a dictionary");
  1403. return NULL;
  1404. }
  1405. pyexpat_state *state = pyexpat_get_state(module);
  1406. result = newxmlparseobject(state, encoding, namespace_separator, intern);
  1407. if (intern_decref) {
  1408. Py_DECREF(intern);
  1409. }
  1410. return result;
  1411. }
  1412. /*[clinic input]
  1413. pyexpat.ErrorString
  1414. code: long
  1415. /
  1416. Returns string error for given number.
  1417. [clinic start generated code]*/
  1418. static PyObject *
  1419. pyexpat_ErrorString_impl(PyObject *module, long code)
  1420. /*[clinic end generated code: output=2feae50d166f2174 input=cc67de010d9e62b3]*/
  1421. {
  1422. return Py_BuildValue("z", XML_ErrorString((int)code));
  1423. }
  1424. /* List of methods defined in the module */
  1425. static struct PyMethodDef pyexpat_methods[] = {
  1426. PYEXPAT_PARSERCREATE_METHODDEF
  1427. PYEXPAT_ERRORSTRING_METHODDEF
  1428. {NULL, NULL} /* sentinel */
  1429. };
  1430. /* Module docstring */
  1431. PyDoc_STRVAR(pyexpat_module_documentation,
  1432. "Python wrapper for Expat parser.");
  1433. /* Initialization function for the module */
  1434. #ifndef MODULE_NAME
  1435. #define MODULE_NAME "pyexpat"
  1436. #endif
  1437. static int init_handler_descrs(pyexpat_state *state)
  1438. {
  1439. int i;
  1440. assert(!PyType_HasFeature(state->xml_parse_type, Py_TPFLAGS_VALID_VERSION_TAG));
  1441. for (i = 0; handler_info[i].name != NULL; i++) {
  1442. struct HandlerInfo *hi = &handler_info[i];
  1443. hi->getset.name = hi->name;
  1444. hi->getset.get = (getter)xmlparse_handler_getter;
  1445. hi->getset.set = (setter)xmlparse_handler_setter;
  1446. hi->getset.closure = &handler_info[i];
  1447. PyObject *descr = PyDescr_NewGetSet(state->xml_parse_type, &hi->getset);
  1448. if (descr == NULL)
  1449. return -1;
  1450. if (PyDict_SetDefault(state->xml_parse_type->tp_dict, PyDescr_NAME(descr), descr) == NULL) {
  1451. Py_DECREF(descr);
  1452. return -1;
  1453. }
  1454. Py_DECREF(descr);
  1455. }
  1456. return 0;
  1457. }
  1458. static PyObject *
  1459. add_submodule(PyObject *mod, const char *fullname)
  1460. {
  1461. const char *name = strrchr(fullname, '.') + 1;
  1462. PyObject *submodule = PyModule_New(fullname);
  1463. if (submodule == NULL) {
  1464. return NULL;
  1465. }
  1466. PyObject *mod_name = PyUnicode_FromString(fullname);
  1467. if (mod_name == NULL) {
  1468. Py_DECREF(submodule);
  1469. return NULL;
  1470. }
  1471. if (_PyImport_SetModule(mod_name, submodule) < 0) {
  1472. Py_DECREF(submodule);
  1473. Py_DECREF(mod_name);
  1474. return NULL;
  1475. }
  1476. Py_DECREF(mod_name);
  1477. /* gives away the reference to the submodule */
  1478. if (PyModule_AddObject(mod, name, submodule) < 0) {
  1479. Py_DECREF(submodule);
  1480. return NULL;
  1481. }
  1482. return submodule;
  1483. }
  1484. struct ErrorInfo {
  1485. const char * name; /* Error constant name, e.g. "XML_ERROR_NO_MEMORY" */
  1486. const char * description; /* Error description as returned by XML_ErrorString(<int>) */
  1487. };
  1488. static
  1489. struct ErrorInfo error_info_of[] = {
  1490. {NULL, NULL}, /* XML_ERROR_NONE (value 0) is not exposed */
  1491. {"XML_ERROR_NO_MEMORY", "out of memory"},
  1492. {"XML_ERROR_SYNTAX", "syntax error"},
  1493. {"XML_ERROR_NO_ELEMENTS", "no element found"},
  1494. {"XML_ERROR_INVALID_TOKEN", "not well-formed (invalid token)"},
  1495. {"XML_ERROR_UNCLOSED_TOKEN", "unclosed token"},
  1496. {"XML_ERROR_PARTIAL_CHAR", "partial character"},
  1497. {"XML_ERROR_TAG_MISMATCH", "mismatched tag"},
  1498. {"XML_ERROR_DUPLICATE_ATTRIBUTE", "duplicate attribute"},
  1499. {"XML_ERROR_JUNK_AFTER_DOC_ELEMENT", "junk after document element"},
  1500. {"XML_ERROR_PARAM_ENTITY_REF", "illegal parameter entity reference"},
  1501. {"XML_ERROR_UNDEFINED_ENTITY", "undefined entity"},
  1502. {"XML_ERROR_RECURSIVE_ENTITY_REF", "recursive entity reference"},
  1503. {"XML_ERROR_ASYNC_ENTITY", "asynchronous entity"},
  1504. {"XML_ERROR_BAD_CHAR_REF", "reference to invalid character number"},
  1505. {"XML_ERROR_BINARY_ENTITY_REF", "reference to binary entity"},
  1506. {"XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF", "reference to external entity in attribute"},
  1507. {"XML_ERROR_MISPLACED_XML_PI", "XML or text declaration not at start of entity"},
  1508. {"XML_ERROR_UNKNOWN_ENCODING", "unknown encoding"},
  1509. {"XML_ERROR_INCORRECT_ENCODING", "encoding specified in XML declaration is incorrect"},
  1510. {"XML_ERROR_UNCLOSED_CDATA_SECTION", "unclosed CDATA section"},
  1511. {"XML_ERROR_EXTERNAL_ENTITY_HANDLING", "error in processing external entity reference"},
  1512. {"XML_ERROR_NOT_STANDALONE", "document is not standalone"},
  1513. {"XML_ERROR_UNEXPECTED_STATE", "unexpected parser state - please send a bug report"},
  1514. {"XML_ERROR_ENTITY_DECLARED_IN_PE", "entity declared in parameter entity"},
  1515. {"XML_ERROR_FEATURE_REQUIRES_XML_DTD", "requested feature requires XML_DTD support in Expat"},
  1516. {"XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING", "cannot change setting once parsing has begun"},
  1517. /* Added in Expat 1.95.7. */
  1518. {"XML_ERROR_UNBOUND_PREFIX", "unbound prefix"},
  1519. /* Added in Expat 1.95.8. */
  1520. {"XML_ERROR_UNDECLARING_PREFIX", "must not undeclare prefix"},
  1521. {"XML_ERROR_INCOMPLETE_PE", "incomplete markup in parameter entity"},
  1522. {"XML_ERROR_XML_DECL", "XML declaration not well-formed"},
  1523. {"XML_ERROR_TEXT_DECL", "text declaration not well-formed"},
  1524. {"XML_ERROR_PUBLICID", "illegal character(s) in public id"},
  1525. {"XML_ERROR_SUSPENDED", "parser suspended"},
  1526. {"XML_ERROR_NOT_SUSPENDED", "parser not suspended"},
  1527. {"XML_ERROR_ABORTED", "parsing aborted"},
  1528. {"XML_ERROR_FINISHED", "parsing finished"},
  1529. {"XML_ERROR_SUSPEND_PE", "cannot suspend in external parameter entity"},
  1530. /* Added in 2.0.0. */
  1531. {"XML_ERROR_RESERVED_PREFIX_XML", "reserved prefix (xml) must not be undeclared or bound to another namespace name"},
  1532. {"XML_ERROR_RESERVED_PREFIX_XMLNS", "reserved prefix (xmlns) must not be declared or undeclared"},
  1533. {"XML_ERROR_RESERVED_NAMESPACE_URI", "prefix must not be bound to one of the reserved namespace names"},
  1534. /* Added in 2.2.1. */
  1535. {"XML_ERROR_INVALID_ARGUMENT", "invalid argument"},
  1536. /* Added in 2.3.0. */
  1537. {"XML_ERROR_NO_BUFFER", "a successful prior call to function XML_GetBuffer is required"},
  1538. /* Added in 2.4.0. */
  1539. {"XML_ERROR_AMPLIFICATION_LIMIT_BREACH", "limit on input amplification factor (from DTD and entities) breached"}
  1540. };
  1541. static int
  1542. add_error(PyObject *errors_module, PyObject *codes_dict,
  1543. PyObject *rev_codes_dict, size_t error_index)
  1544. {
  1545. const char * const name = error_info_of[error_index].name;
  1546. const int error_code = (int)error_index;
  1547. /* NOTE: This keeps the source of truth regarding error
  1548. * messages with libexpat and (by definition) in bulletproof sync
  1549. * with the other uses of the XML_ErrorString function
  1550. * elsewhere within this file. pyexpat's copy of the messages
  1551. * only acts as a fallback in case of outdated runtime libexpat,
  1552. * where it returns NULL. */
  1553. const char *error_string = XML_ErrorString(error_code);
  1554. if (error_string == NULL) {
  1555. error_string = error_info_of[error_index].description;
  1556. }
  1557. if (PyModule_AddStringConstant(errors_module, name, error_string) < 0) {
  1558. return -1;
  1559. }
  1560. PyObject *num = PyLong_FromLong(error_code);
  1561. if (num == NULL) {
  1562. return -1;
  1563. }
  1564. if (PyDict_SetItemString(codes_dict, error_string, num) < 0) {
  1565. Py_DECREF(num);
  1566. return -1;
  1567. }
  1568. PyObject *str = PyUnicode_FromString(error_string);
  1569. if (str == NULL) {
  1570. Py_DECREF(num);
  1571. return -1;
  1572. }
  1573. int res = PyDict_SetItem(rev_codes_dict, num, str);
  1574. Py_DECREF(str);
  1575. Py_DECREF(num);
  1576. if (res < 0) {
  1577. return -1;
  1578. }
  1579. return 0;
  1580. }
  1581. static int
  1582. add_errors_module(PyObject *mod)
  1583. {
  1584. // add_submodule() returns a borrowed ref.
  1585. PyObject *errors_module = add_submodule(mod, MODULE_NAME ".errors");
  1586. if (errors_module == NULL) {
  1587. return -1;
  1588. }
  1589. PyObject *codes_dict = PyDict_New();
  1590. if (codes_dict == NULL) {
  1591. return -1;
  1592. }
  1593. PyObject *rev_codes_dict = PyDict_New();
  1594. if (rev_codes_dict == NULL) {
  1595. goto error;
  1596. }
  1597. size_t error_index = 0;
  1598. for (; error_index < sizeof(error_info_of) / sizeof(struct ErrorInfo); error_index++) {
  1599. if (error_info_of[error_index].name == NULL) {
  1600. continue;
  1601. }
  1602. if (add_error(errors_module, codes_dict, rev_codes_dict, error_index) < 0) {
  1603. goto error;
  1604. }
  1605. }
  1606. if (PyModule_AddStringConstant(errors_module, "__doc__",
  1607. "Constants used to describe "
  1608. "error conditions.") < 0) {
  1609. goto error;
  1610. }
  1611. int rc = PyModule_AddObjectRef(errors_module, "codes", codes_dict);
  1612. Py_CLEAR(codes_dict);
  1613. if (rc < 0) {
  1614. goto error;
  1615. }
  1616. rc = PyModule_AddObjectRef(errors_module, "messages", rev_codes_dict);
  1617. Py_CLEAR(rev_codes_dict);
  1618. if (rc < 0) {
  1619. goto error;
  1620. }
  1621. return 0;
  1622. error:
  1623. Py_XDECREF(codes_dict);
  1624. Py_XDECREF(rev_codes_dict);
  1625. return -1;
  1626. }
  1627. static int
  1628. add_model_module(PyObject *mod)
  1629. {
  1630. PyObject *model_module = add_submodule(mod, MODULE_NAME ".model");
  1631. if (model_module == NULL) {
  1632. return -1;
  1633. }
  1634. #define MYCONST(c) do { \
  1635. if (PyModule_AddIntConstant(model_module, #c, c) < 0) { \
  1636. return -1; \
  1637. } \
  1638. } while(0)
  1639. if (PyModule_AddStringConstant(
  1640. model_module, "__doc__",
  1641. "Constants used to interpret content model information.") < 0) {
  1642. return -1;
  1643. }
  1644. MYCONST(XML_CTYPE_EMPTY);
  1645. MYCONST(XML_CTYPE_ANY);
  1646. MYCONST(XML_CTYPE_MIXED);
  1647. MYCONST(XML_CTYPE_NAME);
  1648. MYCONST(XML_CTYPE_CHOICE);
  1649. MYCONST(XML_CTYPE_SEQ);
  1650. MYCONST(XML_CQUANT_NONE);
  1651. MYCONST(XML_CQUANT_OPT);
  1652. MYCONST(XML_CQUANT_REP);
  1653. MYCONST(XML_CQUANT_PLUS);
  1654. #undef MYCONST
  1655. return 0;
  1656. }
  1657. #if XML_COMBINED_VERSION > 19505
  1658. static int
  1659. add_features(PyObject *mod)
  1660. {
  1661. PyObject *list = PyList_New(0);
  1662. if (list == NULL) {
  1663. return -1;
  1664. }
  1665. const XML_Feature *features = XML_GetFeatureList();
  1666. for (size_t i = 0; features[i].feature != XML_FEATURE_END; ++i) {
  1667. PyObject *item = Py_BuildValue("si", features[i].name,
  1668. features[i].value);
  1669. if (item == NULL) {
  1670. goto error;
  1671. }
  1672. int ok = PyList_Append(list, item);
  1673. Py_DECREF(item);
  1674. if (ok < 0) {
  1675. goto error;
  1676. }
  1677. }
  1678. if (PyModule_AddObject(mod, "features", list) < 0) {
  1679. goto error;
  1680. }
  1681. return 0;
  1682. error:
  1683. Py_DECREF(list);
  1684. return -1;
  1685. }
  1686. #endif
  1687. static void
  1688. pyexpat_capsule_destructor(PyObject *capsule)
  1689. {
  1690. void *p = PyCapsule_GetPointer(capsule, PyExpat_CAPSULE_NAME);
  1691. if (p == NULL) {
  1692. PyErr_WriteUnraisable(capsule);
  1693. return;
  1694. }
  1695. PyMem_Free(p);
  1696. }
  1697. static int
  1698. pyexpat_exec(PyObject *mod)
  1699. {
  1700. pyexpat_state *state = pyexpat_get_state(mod);
  1701. state->str_read = PyUnicode_InternFromString("read");
  1702. if (state->str_read == NULL) {
  1703. return -1;
  1704. }
  1705. state->xml_parse_type = (PyTypeObject *)PyType_FromModuleAndSpec(
  1706. mod, &_xml_parse_type_spec, NULL);
  1707. if (state->xml_parse_type == NULL) {
  1708. return -1;
  1709. }
  1710. if (init_handler_descrs(state) < 0) {
  1711. return -1;
  1712. }
  1713. state->error = PyErr_NewException("xml.parsers.expat.ExpatError",
  1714. NULL, NULL);
  1715. if (state->error == NULL) {
  1716. return -1;
  1717. }
  1718. /* Add some symbolic constants to the module */
  1719. if (PyModule_AddObjectRef(mod, "error", state->error) < 0) {
  1720. return -1;
  1721. }
  1722. if (PyModule_AddObjectRef(mod, "ExpatError", state->error) < 0) {
  1723. return -1;
  1724. }
  1725. if (PyModule_AddObjectRef(mod, "XMLParserType",
  1726. (PyObject *) state->xml_parse_type) < 0) {
  1727. return -1;
  1728. }
  1729. if (PyModule_AddStringConstant(mod, "EXPAT_VERSION",
  1730. XML_ExpatVersion()) < 0) {
  1731. return -1;
  1732. }
  1733. {
  1734. XML_Expat_Version info = XML_ExpatVersionInfo();
  1735. PyObject *versionInfo = Py_BuildValue("(iii)",
  1736. info.major,
  1737. info.minor,
  1738. info.micro);
  1739. if (PyModule_AddObject(mod, "version_info", versionInfo) < 0) {
  1740. Py_DECREF(versionInfo);
  1741. return -1;
  1742. }
  1743. }
  1744. /* XXX When Expat supports some way of figuring out how it was
  1745. compiled, this should check and set native_encoding
  1746. appropriately.
  1747. */
  1748. if (PyModule_AddStringConstant(mod, "native_encoding", "UTF-8") < 0) {
  1749. return -1;
  1750. }
  1751. if (add_errors_module(mod) < 0) {
  1752. return -1;
  1753. }
  1754. if (add_model_module(mod) < 0) {
  1755. return -1;
  1756. }
  1757. #if XML_COMBINED_VERSION > 19505
  1758. if (add_features(mod) < 0) {
  1759. return -1;
  1760. }
  1761. #endif
  1762. #define MYCONST(c) do { \
  1763. if (PyModule_AddIntConstant(mod, #c, c) < 0) { \
  1764. return -1; \
  1765. } \
  1766. } while(0)
  1767. MYCONST(XML_PARAM_ENTITY_PARSING_NEVER);
  1768. MYCONST(XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE);
  1769. MYCONST(XML_PARAM_ENTITY_PARSING_ALWAYS);
  1770. #undef MYCONST
  1771. struct PyExpat_CAPI *capi = PyMem_Malloc(sizeof(*capi));
  1772. if (capi == NULL) {
  1773. PyErr_NoMemory();
  1774. return -1;
  1775. }
  1776. /* initialize pyexpat dispatch table */
  1777. capi->size = sizeof(*capi);
  1778. capi->magic = PyExpat_CAPI_MAGIC;
  1779. capi->MAJOR_VERSION = XML_MAJOR_VERSION;
  1780. capi->MINOR_VERSION = XML_MINOR_VERSION;
  1781. capi->MICRO_VERSION = XML_MICRO_VERSION;
  1782. capi->ErrorString = XML_ErrorString;
  1783. capi->GetErrorCode = XML_GetErrorCode;
  1784. capi->GetErrorColumnNumber = XML_GetErrorColumnNumber;
  1785. capi->GetErrorLineNumber = XML_GetErrorLineNumber;
  1786. capi->Parse = XML_Parse;
  1787. capi->ParserCreate_MM = XML_ParserCreate_MM;
  1788. capi->ParserFree = XML_ParserFree;
  1789. capi->SetCharacterDataHandler = XML_SetCharacterDataHandler;
  1790. capi->SetCommentHandler = XML_SetCommentHandler;
  1791. capi->SetDefaultHandlerExpand = XML_SetDefaultHandlerExpand;
  1792. capi->SetElementHandler = XML_SetElementHandler;
  1793. capi->SetNamespaceDeclHandler = XML_SetNamespaceDeclHandler;
  1794. capi->SetProcessingInstructionHandler = XML_SetProcessingInstructionHandler;
  1795. capi->SetUnknownEncodingHandler = XML_SetUnknownEncodingHandler;
  1796. capi->SetUserData = XML_SetUserData;
  1797. capi->SetStartDoctypeDeclHandler = XML_SetStartDoctypeDeclHandler;
  1798. capi->SetEncoding = XML_SetEncoding;
  1799. capi->DefaultUnknownEncodingHandler = PyUnknownEncodingHandler;
  1800. #if XML_COMBINED_VERSION >= 20100
  1801. capi->SetHashSalt = XML_SetHashSalt;
  1802. #else
  1803. capi->SetHashSalt = NULL;
  1804. #endif
  1805. #if XML_COMBINED_VERSION >= 20600
  1806. capi->SetReparseDeferralEnabled = XML_SetReparseDeferralEnabled;
  1807. #else
  1808. capi->SetReparseDeferralEnabled = NULL;
  1809. #endif
  1810. /* export using capsule */
  1811. PyObject *capi_object = PyCapsule_New(capi, PyExpat_CAPSULE_NAME,
  1812. pyexpat_capsule_destructor);
  1813. if (capi_object == NULL) {
  1814. PyMem_Free(capi);
  1815. return -1;
  1816. }
  1817. if (PyModule_AddObject(mod, "expat_CAPI", capi_object) < 0) {
  1818. Py_DECREF(capi_object);
  1819. return -1;
  1820. }
  1821. return 0;
  1822. }
  1823. static int
  1824. pyexpat_traverse(PyObject *module, visitproc visit, void *arg)
  1825. {
  1826. pyexpat_state *state = pyexpat_get_state(module);
  1827. Py_VISIT(state->xml_parse_type);
  1828. Py_VISIT(state->error);
  1829. Py_VISIT(state->str_read);
  1830. return 0;
  1831. }
  1832. static int
  1833. pyexpat_clear(PyObject *module)
  1834. {
  1835. pyexpat_state *state = pyexpat_get_state(module);
  1836. Py_CLEAR(state->xml_parse_type);
  1837. Py_CLEAR(state->error);
  1838. Py_CLEAR(state->str_read);
  1839. return 0;
  1840. }
  1841. static void
  1842. pyexpat_free(void *module)
  1843. {
  1844. pyexpat_clear((PyObject *)module);
  1845. }
  1846. static PyModuleDef_Slot pyexpat_slots[] = {
  1847. {Py_mod_exec, pyexpat_exec},
  1848. // XXX gh-103092: fix isolation.
  1849. {Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED},
  1850. //{Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  1851. {0, NULL}
  1852. };
  1853. static struct PyModuleDef pyexpatmodule = {
  1854. PyModuleDef_HEAD_INIT,
  1855. .m_name = MODULE_NAME,
  1856. .m_doc = pyexpat_module_documentation,
  1857. .m_size = sizeof(pyexpat_state),
  1858. .m_methods = pyexpat_methods,
  1859. .m_slots = pyexpat_slots,
  1860. .m_traverse = pyexpat_traverse,
  1861. .m_clear = pyexpat_clear,
  1862. .m_free = pyexpat_free
  1863. };
  1864. PyMODINIT_FUNC
  1865. PyInit_pyexpat(void)
  1866. {
  1867. return PyModuleDef_Init(&pyexpatmodule);
  1868. }
  1869. static void
  1870. clear_handlers(xmlparseobject *self, int initial)
  1871. {
  1872. int i = 0;
  1873. for (; handler_info[i].name != NULL; i++) {
  1874. if (initial)
  1875. self->handlers[i] = NULL;
  1876. else {
  1877. Py_CLEAR(self->handlers[i]);
  1878. handler_info[i].setter(self->itself, NULL);
  1879. }
  1880. }
  1881. }
  1882. static struct HandlerInfo handler_info[] = {
  1883. #define HANDLER_INFO(name) \
  1884. {#name, (xmlhandlersetter)XML_Set##name, (xmlhandler)my_##name},
  1885. HANDLER_INFO(StartElementHandler)
  1886. HANDLER_INFO(EndElementHandler)
  1887. HANDLER_INFO(ProcessingInstructionHandler)
  1888. HANDLER_INFO(CharacterDataHandler)
  1889. HANDLER_INFO(UnparsedEntityDeclHandler)
  1890. HANDLER_INFO(NotationDeclHandler)
  1891. HANDLER_INFO(StartNamespaceDeclHandler)
  1892. HANDLER_INFO(EndNamespaceDeclHandler)
  1893. HANDLER_INFO(CommentHandler)
  1894. HANDLER_INFO(StartCdataSectionHandler)
  1895. HANDLER_INFO(EndCdataSectionHandler)
  1896. HANDLER_INFO(DefaultHandler)
  1897. HANDLER_INFO(DefaultHandlerExpand)
  1898. HANDLER_INFO(NotStandaloneHandler)
  1899. HANDLER_INFO(ExternalEntityRefHandler)
  1900. HANDLER_INFO(StartDoctypeDeclHandler)
  1901. HANDLER_INFO(EndDoctypeDeclHandler)
  1902. HANDLER_INFO(EntityDeclHandler)
  1903. HANDLER_INFO(XmlDeclHandler)
  1904. HANDLER_INFO(ElementDeclHandler)
  1905. HANDLER_INFO(AttlistDeclHandler)
  1906. #if XML_COMBINED_VERSION >= 19504
  1907. HANDLER_INFO(SkippedEntityHandler)
  1908. #endif
  1909. #undef HANDLER_INFO
  1910. {NULL, NULL, NULL} /* sentinel */
  1911. };