pyexpat.c 63 KB

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