codecs.c 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520
  1. /* ------------------------------------------------------------------------
  2. Python Codec Registry and support functions
  3. Written by Marc-Andre Lemburg (mal@lemburg.com).
  4. Copyright (c) Corporation for National Research Initiatives.
  5. ------------------------------------------------------------------------ */
  6. #include "Python.h"
  7. #include "pycore_call.h" // _PyObject_CallNoArgs()
  8. #include "pycore_interp.h" // PyInterpreterState.codec_search_path
  9. #include "pycore_pyerrors.h" // _PyErr_FormatNote()
  10. #include "pycore_pystate.h" // _PyInterpreterState_GET()
  11. #include "pycore_ucnhash.h" // _PyUnicode_Name_CAPI
  12. #include <ctype.h>
  13. const char *Py_hexdigits = "0123456789abcdef";
  14. /* --- Codec Registry ----------------------------------------------------- */
  15. /* Import the standard encodings package which will register the first
  16. codec search function.
  17. This is done in a lazy way so that the Unicode implementation does
  18. not downgrade startup time of scripts not needing it.
  19. ImportErrors are silently ignored by this function. Only one try is
  20. made.
  21. */
  22. static int _PyCodecRegistry_Init(void); /* Forward */
  23. int PyCodec_Register(PyObject *search_function)
  24. {
  25. PyInterpreterState *interp = _PyInterpreterState_GET();
  26. if (interp->codec_search_path == NULL && _PyCodecRegistry_Init())
  27. goto onError;
  28. if (search_function == NULL) {
  29. PyErr_BadArgument();
  30. goto onError;
  31. }
  32. if (!PyCallable_Check(search_function)) {
  33. PyErr_SetString(PyExc_TypeError, "argument must be callable");
  34. goto onError;
  35. }
  36. return PyList_Append(interp->codec_search_path, search_function);
  37. onError:
  38. return -1;
  39. }
  40. int
  41. PyCodec_Unregister(PyObject *search_function)
  42. {
  43. PyInterpreterState *interp = PyInterpreterState_Get();
  44. PyObject *codec_search_path = interp->codec_search_path;
  45. /* Do nothing if codec_search_path is not created yet or was cleared. */
  46. if (codec_search_path == NULL) {
  47. return 0;
  48. }
  49. assert(PyList_CheckExact(codec_search_path));
  50. Py_ssize_t n = PyList_GET_SIZE(codec_search_path);
  51. for (Py_ssize_t i = 0; i < n; i++) {
  52. PyObject *item = PyList_GET_ITEM(codec_search_path, i);
  53. if (item == search_function) {
  54. if (interp->codec_search_cache != NULL) {
  55. assert(PyDict_CheckExact(interp->codec_search_cache));
  56. PyDict_Clear(interp->codec_search_cache);
  57. }
  58. return PyList_SetSlice(codec_search_path, i, i+1, NULL);
  59. }
  60. }
  61. return 0;
  62. }
  63. extern int _Py_normalize_encoding(const char *, char *, size_t);
  64. /* Convert a string to a normalized Python string(decoded from UTF-8): all characters are
  65. converted to lower case, spaces and hyphens are replaced with underscores. */
  66. static
  67. PyObject *normalizestring(const char *string)
  68. {
  69. size_t len = strlen(string);
  70. char *encoding;
  71. PyObject *v;
  72. if (len > PY_SSIZE_T_MAX) {
  73. PyErr_SetString(PyExc_OverflowError, "string is too large");
  74. return NULL;
  75. }
  76. encoding = PyMem_Malloc(len + 1);
  77. if (encoding == NULL)
  78. return PyErr_NoMemory();
  79. if (!_Py_normalize_encoding(string, encoding, len + 1))
  80. {
  81. PyErr_SetString(PyExc_RuntimeError, "_Py_normalize_encoding() failed");
  82. PyMem_Free(encoding);
  83. return NULL;
  84. }
  85. v = PyUnicode_FromString(encoding);
  86. PyMem_Free(encoding);
  87. return v;
  88. }
  89. /* Lookup the given encoding and return a tuple providing the codec
  90. facilities.
  91. The encoding string is looked up converted to all lower-case
  92. characters. This makes encodings looked up through this mechanism
  93. effectively case-insensitive.
  94. If no codec is found, a LookupError is set and NULL returned.
  95. As side effect, this tries to load the encodings package, if not
  96. yet done. This is part of the lazy load strategy for the encodings
  97. package.
  98. */
  99. PyObject *_PyCodec_Lookup(const char *encoding)
  100. {
  101. if (encoding == NULL) {
  102. PyErr_BadArgument();
  103. return NULL;
  104. }
  105. PyInterpreterState *interp = _PyInterpreterState_GET();
  106. if (interp->codec_search_path == NULL && _PyCodecRegistry_Init()) {
  107. return NULL;
  108. }
  109. /* Convert the encoding to a normalized Python string: all
  110. characters are converted to lower case, spaces and hyphens are
  111. replaced with underscores. */
  112. PyObject *v = normalizestring(encoding);
  113. if (v == NULL) {
  114. return NULL;
  115. }
  116. /* Intern the string. We'll make it immortal later if lookup succeeds. */
  117. _PyUnicode_InternMortal(interp, &v);
  118. /* First, try to lookup the name in the registry dictionary */
  119. PyObject *result = PyDict_GetItemWithError(interp->codec_search_cache, v);
  120. if (result != NULL) {
  121. Py_INCREF(result);
  122. Py_DECREF(v);
  123. return result;
  124. }
  125. else if (PyErr_Occurred()) {
  126. goto onError;
  127. }
  128. /* Next, scan the search functions in order of registration */
  129. const Py_ssize_t len = PyList_Size(interp->codec_search_path);
  130. if (len < 0)
  131. goto onError;
  132. if (len == 0) {
  133. PyErr_SetString(PyExc_LookupError,
  134. "no codec search functions registered: "
  135. "can't find encoding");
  136. goto onError;
  137. }
  138. Py_ssize_t i;
  139. for (i = 0; i < len; i++) {
  140. PyObject *func;
  141. func = PyList_GetItem(interp->codec_search_path, i);
  142. if (func == NULL)
  143. goto onError;
  144. result = PyObject_CallOneArg(func, v);
  145. if (result == NULL)
  146. goto onError;
  147. if (result == Py_None) {
  148. Py_DECREF(result);
  149. continue;
  150. }
  151. if (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 4) {
  152. PyErr_SetString(PyExc_TypeError,
  153. "codec search functions must return 4-tuples");
  154. Py_DECREF(result);
  155. goto onError;
  156. }
  157. break;
  158. }
  159. if (i == len) {
  160. /* XXX Perhaps we should cache misses too ? */
  161. PyErr_Format(PyExc_LookupError,
  162. "unknown encoding: %s", encoding);
  163. goto onError;
  164. }
  165. _PyUnicode_InternImmortal(interp, &v);
  166. /* Cache and return the result */
  167. if (PyDict_SetItem(interp->codec_search_cache, v, result) < 0) {
  168. Py_DECREF(result);
  169. goto onError;
  170. }
  171. Py_DECREF(v);
  172. return result;
  173. onError:
  174. Py_DECREF(v);
  175. return NULL;
  176. }
  177. /* Codec registry encoding check API. */
  178. int PyCodec_KnownEncoding(const char *encoding)
  179. {
  180. PyObject *codecs;
  181. codecs = _PyCodec_Lookup(encoding);
  182. if (!codecs) {
  183. PyErr_Clear();
  184. return 0;
  185. }
  186. else {
  187. Py_DECREF(codecs);
  188. return 1;
  189. }
  190. }
  191. static
  192. PyObject *args_tuple(PyObject *object,
  193. const char *errors)
  194. {
  195. PyObject *args;
  196. args = PyTuple_New(1 + (errors != NULL));
  197. if (args == NULL)
  198. return NULL;
  199. PyTuple_SET_ITEM(args, 0, Py_NewRef(object));
  200. if (errors) {
  201. PyObject *v;
  202. v = PyUnicode_FromString(errors);
  203. if (v == NULL) {
  204. Py_DECREF(args);
  205. return NULL;
  206. }
  207. PyTuple_SET_ITEM(args, 1, v);
  208. }
  209. return args;
  210. }
  211. /* Helper function to get a codec item */
  212. static
  213. PyObject *codec_getitem(const char *encoding, int index)
  214. {
  215. PyObject *codecs;
  216. PyObject *v;
  217. codecs = _PyCodec_Lookup(encoding);
  218. if (codecs == NULL)
  219. return NULL;
  220. v = PyTuple_GET_ITEM(codecs, index);
  221. Py_DECREF(codecs);
  222. return Py_NewRef(v);
  223. }
  224. /* Helper functions to create an incremental codec. */
  225. static
  226. PyObject *codec_makeincrementalcodec(PyObject *codec_info,
  227. const char *errors,
  228. const char *attrname)
  229. {
  230. PyObject *ret, *inccodec;
  231. inccodec = PyObject_GetAttrString(codec_info, attrname);
  232. if (inccodec == NULL)
  233. return NULL;
  234. if (errors)
  235. ret = PyObject_CallFunction(inccodec, "s", errors);
  236. else
  237. ret = _PyObject_CallNoArgs(inccodec);
  238. Py_DECREF(inccodec);
  239. return ret;
  240. }
  241. static
  242. PyObject *codec_getincrementalcodec(const char *encoding,
  243. const char *errors,
  244. const char *attrname)
  245. {
  246. PyObject *codec_info, *ret;
  247. codec_info = _PyCodec_Lookup(encoding);
  248. if (codec_info == NULL)
  249. return NULL;
  250. ret = codec_makeincrementalcodec(codec_info, errors, attrname);
  251. Py_DECREF(codec_info);
  252. return ret;
  253. }
  254. /* Helper function to create a stream codec. */
  255. static
  256. PyObject *codec_getstreamcodec(const char *encoding,
  257. PyObject *stream,
  258. const char *errors,
  259. const int index)
  260. {
  261. PyObject *codecs, *streamcodec, *codeccls;
  262. codecs = _PyCodec_Lookup(encoding);
  263. if (codecs == NULL)
  264. return NULL;
  265. codeccls = PyTuple_GET_ITEM(codecs, index);
  266. if (errors != NULL)
  267. streamcodec = PyObject_CallFunction(codeccls, "Os", stream, errors);
  268. else
  269. streamcodec = PyObject_CallOneArg(codeccls, stream);
  270. Py_DECREF(codecs);
  271. return streamcodec;
  272. }
  273. /* Helpers to work with the result of _PyCodec_Lookup
  274. */
  275. PyObject *_PyCodecInfo_GetIncrementalDecoder(PyObject *codec_info,
  276. const char *errors)
  277. {
  278. return codec_makeincrementalcodec(codec_info, errors,
  279. "incrementaldecoder");
  280. }
  281. PyObject *_PyCodecInfo_GetIncrementalEncoder(PyObject *codec_info,
  282. const char *errors)
  283. {
  284. return codec_makeincrementalcodec(codec_info, errors,
  285. "incrementalencoder");
  286. }
  287. /* Convenience APIs to query the Codec registry.
  288. All APIs return a codec object with incremented refcount.
  289. */
  290. PyObject *PyCodec_Encoder(const char *encoding)
  291. {
  292. return codec_getitem(encoding, 0);
  293. }
  294. PyObject *PyCodec_Decoder(const char *encoding)
  295. {
  296. return codec_getitem(encoding, 1);
  297. }
  298. PyObject *PyCodec_IncrementalEncoder(const char *encoding,
  299. const char *errors)
  300. {
  301. return codec_getincrementalcodec(encoding, errors, "incrementalencoder");
  302. }
  303. PyObject *PyCodec_IncrementalDecoder(const char *encoding,
  304. const char *errors)
  305. {
  306. return codec_getincrementalcodec(encoding, errors, "incrementaldecoder");
  307. }
  308. PyObject *PyCodec_StreamReader(const char *encoding,
  309. PyObject *stream,
  310. const char *errors)
  311. {
  312. return codec_getstreamcodec(encoding, stream, errors, 2);
  313. }
  314. PyObject *PyCodec_StreamWriter(const char *encoding,
  315. PyObject *stream,
  316. const char *errors)
  317. {
  318. return codec_getstreamcodec(encoding, stream, errors, 3);
  319. }
  320. /* Encode an object (e.g. a Unicode object) using the given encoding
  321. and return the resulting encoded object (usually a Python string).
  322. errors is passed to the encoder factory as argument if non-NULL. */
  323. static PyObject *
  324. _PyCodec_EncodeInternal(PyObject *object,
  325. PyObject *encoder,
  326. const char *encoding,
  327. const char *errors)
  328. {
  329. PyObject *args = NULL, *result = NULL;
  330. PyObject *v = NULL;
  331. args = args_tuple(object, errors);
  332. if (args == NULL)
  333. goto onError;
  334. result = PyObject_Call(encoder, args, NULL);
  335. if (result == NULL) {
  336. _PyErr_FormatNote("%s with '%s' codec failed", "encoding", encoding);
  337. goto onError;
  338. }
  339. if (!PyTuple_Check(result) ||
  340. PyTuple_GET_SIZE(result) != 2) {
  341. PyErr_SetString(PyExc_TypeError,
  342. "encoder must return a tuple (object, integer)");
  343. goto onError;
  344. }
  345. v = Py_NewRef(PyTuple_GET_ITEM(result,0));
  346. /* We don't check or use the second (integer) entry. */
  347. Py_DECREF(args);
  348. Py_DECREF(encoder);
  349. Py_DECREF(result);
  350. return v;
  351. onError:
  352. Py_XDECREF(result);
  353. Py_XDECREF(args);
  354. Py_XDECREF(encoder);
  355. return NULL;
  356. }
  357. /* Decode an object (usually a Python string) using the given encoding
  358. and return an equivalent object (e.g. a Unicode object).
  359. errors is passed to the decoder factory as argument if non-NULL. */
  360. static PyObject *
  361. _PyCodec_DecodeInternal(PyObject *object,
  362. PyObject *decoder,
  363. const char *encoding,
  364. const char *errors)
  365. {
  366. PyObject *args = NULL, *result = NULL;
  367. PyObject *v;
  368. args = args_tuple(object, errors);
  369. if (args == NULL)
  370. goto onError;
  371. result = PyObject_Call(decoder, args, NULL);
  372. if (result == NULL) {
  373. _PyErr_FormatNote("%s with '%s' codec failed", "decoding", encoding);
  374. goto onError;
  375. }
  376. if (!PyTuple_Check(result) ||
  377. PyTuple_GET_SIZE(result) != 2) {
  378. PyErr_SetString(PyExc_TypeError,
  379. "decoder must return a tuple (object,integer)");
  380. goto onError;
  381. }
  382. v = Py_NewRef(PyTuple_GET_ITEM(result,0));
  383. /* We don't check or use the second (integer) entry. */
  384. Py_DECREF(args);
  385. Py_DECREF(decoder);
  386. Py_DECREF(result);
  387. return v;
  388. onError:
  389. Py_XDECREF(args);
  390. Py_XDECREF(decoder);
  391. Py_XDECREF(result);
  392. return NULL;
  393. }
  394. /* Generic encoding/decoding API */
  395. PyObject *PyCodec_Encode(PyObject *object,
  396. const char *encoding,
  397. const char *errors)
  398. {
  399. PyObject *encoder;
  400. encoder = PyCodec_Encoder(encoding);
  401. if (encoder == NULL)
  402. return NULL;
  403. return _PyCodec_EncodeInternal(object, encoder, encoding, errors);
  404. }
  405. PyObject *PyCodec_Decode(PyObject *object,
  406. const char *encoding,
  407. const char *errors)
  408. {
  409. PyObject *decoder;
  410. decoder = PyCodec_Decoder(encoding);
  411. if (decoder == NULL)
  412. return NULL;
  413. return _PyCodec_DecodeInternal(object, decoder, encoding, errors);
  414. }
  415. /* Text encoding/decoding API */
  416. PyObject * _PyCodec_LookupTextEncoding(const char *encoding,
  417. const char *alternate_command)
  418. {
  419. PyObject *codec;
  420. PyObject *attr;
  421. int is_text_codec;
  422. codec = _PyCodec_Lookup(encoding);
  423. if (codec == NULL)
  424. return NULL;
  425. /* Backwards compatibility: assume any raw tuple describes a text
  426. * encoding, and the same for anything lacking the private
  427. * attribute.
  428. */
  429. if (!PyTuple_CheckExact(codec)) {
  430. if (_PyObject_LookupAttr(codec, &_Py_ID(_is_text_encoding), &attr) < 0) {
  431. Py_DECREF(codec);
  432. return NULL;
  433. }
  434. if (attr != NULL) {
  435. is_text_codec = PyObject_IsTrue(attr);
  436. Py_DECREF(attr);
  437. if (is_text_codec <= 0) {
  438. Py_DECREF(codec);
  439. if (!is_text_codec)
  440. PyErr_Format(PyExc_LookupError,
  441. "'%.400s' is not a text encoding; "
  442. "use %s to handle arbitrary codecs",
  443. encoding, alternate_command);
  444. return NULL;
  445. }
  446. }
  447. }
  448. /* This appears to be a valid text encoding */
  449. return codec;
  450. }
  451. static
  452. PyObject *codec_getitem_checked(const char *encoding,
  453. const char *alternate_command,
  454. int index)
  455. {
  456. PyObject *codec;
  457. PyObject *v;
  458. codec = _PyCodec_LookupTextEncoding(encoding, alternate_command);
  459. if (codec == NULL)
  460. return NULL;
  461. v = Py_NewRef(PyTuple_GET_ITEM(codec, index));
  462. Py_DECREF(codec);
  463. return v;
  464. }
  465. static PyObject * _PyCodec_TextEncoder(const char *encoding)
  466. {
  467. return codec_getitem_checked(encoding, "codecs.encode()", 0);
  468. }
  469. static PyObject * _PyCodec_TextDecoder(const char *encoding)
  470. {
  471. return codec_getitem_checked(encoding, "codecs.decode()", 1);
  472. }
  473. PyObject *_PyCodec_EncodeText(PyObject *object,
  474. const char *encoding,
  475. const char *errors)
  476. {
  477. PyObject *encoder;
  478. encoder = _PyCodec_TextEncoder(encoding);
  479. if (encoder == NULL)
  480. return NULL;
  481. return _PyCodec_EncodeInternal(object, encoder, encoding, errors);
  482. }
  483. PyObject *_PyCodec_DecodeText(PyObject *object,
  484. const char *encoding,
  485. const char *errors)
  486. {
  487. PyObject *decoder;
  488. decoder = _PyCodec_TextDecoder(encoding);
  489. if (decoder == NULL)
  490. return NULL;
  491. return _PyCodec_DecodeInternal(object, decoder, encoding, errors);
  492. }
  493. /* Register the error handling callback function error under the name
  494. name. This function will be called by the codec when it encounters
  495. an unencodable characters/undecodable bytes and doesn't know the
  496. callback name, when name is specified as the error parameter
  497. in the call to the encode/decode function.
  498. Return 0 on success, -1 on error */
  499. int PyCodec_RegisterError(const char *name, PyObject *error)
  500. {
  501. PyInterpreterState *interp = _PyInterpreterState_GET();
  502. if (interp->codec_search_path == NULL && _PyCodecRegistry_Init())
  503. return -1;
  504. if (!PyCallable_Check(error)) {
  505. PyErr_SetString(PyExc_TypeError, "handler must be callable");
  506. return -1;
  507. }
  508. return PyDict_SetItemString(interp->codec_error_registry,
  509. name, error);
  510. }
  511. /* Lookup the error handling callback function registered under the
  512. name error. As a special case NULL can be passed, in which case
  513. the error handling callback for strict encoding will be returned. */
  514. PyObject *PyCodec_LookupError(const char *name)
  515. {
  516. PyObject *handler = NULL;
  517. PyInterpreterState *interp = _PyInterpreterState_GET();
  518. if (interp->codec_search_path == NULL && _PyCodecRegistry_Init())
  519. return NULL;
  520. if (name==NULL)
  521. name = "strict";
  522. handler = _PyDict_GetItemStringWithError(interp->codec_error_registry, name);
  523. if (handler) {
  524. Py_INCREF(handler);
  525. }
  526. else if (!PyErr_Occurred()) {
  527. PyErr_Format(PyExc_LookupError, "unknown error handler name '%.400s'", name);
  528. }
  529. return handler;
  530. }
  531. static void wrong_exception_type(PyObject *exc)
  532. {
  533. PyErr_Format(PyExc_TypeError,
  534. "don't know how to handle %.200s in error callback",
  535. Py_TYPE(exc)->tp_name);
  536. }
  537. PyObject *PyCodec_StrictErrors(PyObject *exc)
  538. {
  539. if (PyExceptionInstance_Check(exc))
  540. PyErr_SetObject(PyExceptionInstance_Class(exc), exc);
  541. else
  542. PyErr_SetString(PyExc_TypeError, "codec must pass exception instance");
  543. return NULL;
  544. }
  545. PyObject *PyCodec_IgnoreErrors(PyObject *exc)
  546. {
  547. Py_ssize_t end;
  548. if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeEncodeError)) {
  549. if (PyUnicodeEncodeError_GetEnd(exc, &end))
  550. return NULL;
  551. }
  552. else if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeDecodeError)) {
  553. if (PyUnicodeDecodeError_GetEnd(exc, &end))
  554. return NULL;
  555. }
  556. else if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeTranslateError)) {
  557. if (PyUnicodeTranslateError_GetEnd(exc, &end))
  558. return NULL;
  559. }
  560. else {
  561. wrong_exception_type(exc);
  562. return NULL;
  563. }
  564. return Py_BuildValue("(Nn)", PyUnicode_New(0, 0), end);
  565. }
  566. PyObject *PyCodec_ReplaceErrors(PyObject *exc)
  567. {
  568. Py_ssize_t start, end, i, len;
  569. if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeEncodeError)) {
  570. PyObject *res;
  571. Py_UCS1 *outp;
  572. if (PyUnicodeEncodeError_GetStart(exc, &start))
  573. return NULL;
  574. if (PyUnicodeEncodeError_GetEnd(exc, &end))
  575. return NULL;
  576. len = end - start;
  577. res = PyUnicode_New(len, '?');
  578. if (res == NULL)
  579. return NULL;
  580. assert(PyUnicode_KIND(res) == PyUnicode_1BYTE_KIND);
  581. outp = PyUnicode_1BYTE_DATA(res);
  582. for (i = 0; i < len; ++i)
  583. outp[i] = '?';
  584. assert(_PyUnicode_CheckConsistency(res, 1));
  585. return Py_BuildValue("(Nn)", res, end);
  586. }
  587. else if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeDecodeError)) {
  588. if (PyUnicodeDecodeError_GetEnd(exc, &end))
  589. return NULL;
  590. return Py_BuildValue("(Cn)",
  591. (int)Py_UNICODE_REPLACEMENT_CHARACTER,
  592. end);
  593. }
  594. else if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeTranslateError)) {
  595. PyObject *res;
  596. Py_UCS2 *outp;
  597. if (PyUnicodeTranslateError_GetStart(exc, &start))
  598. return NULL;
  599. if (PyUnicodeTranslateError_GetEnd(exc, &end))
  600. return NULL;
  601. len = end - start;
  602. res = PyUnicode_New(len, Py_UNICODE_REPLACEMENT_CHARACTER);
  603. if (res == NULL)
  604. return NULL;
  605. assert(PyUnicode_KIND(res) == PyUnicode_2BYTE_KIND);
  606. outp = PyUnicode_2BYTE_DATA(res);
  607. for (i = 0; i < len; i++)
  608. outp[i] = Py_UNICODE_REPLACEMENT_CHARACTER;
  609. assert(_PyUnicode_CheckConsistency(res, 1));
  610. return Py_BuildValue("(Nn)", res, end);
  611. }
  612. else {
  613. wrong_exception_type(exc);
  614. return NULL;
  615. }
  616. }
  617. PyObject *PyCodec_XMLCharRefReplaceErrors(PyObject *exc)
  618. {
  619. if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeEncodeError)) {
  620. PyObject *restuple;
  621. PyObject *object;
  622. Py_ssize_t i;
  623. Py_ssize_t start;
  624. Py_ssize_t end;
  625. PyObject *res;
  626. Py_UCS1 *outp;
  627. Py_ssize_t ressize;
  628. Py_UCS4 ch;
  629. if (PyUnicodeEncodeError_GetStart(exc, &start))
  630. return NULL;
  631. if (PyUnicodeEncodeError_GetEnd(exc, &end))
  632. return NULL;
  633. if (!(object = PyUnicodeEncodeError_GetObject(exc)))
  634. return NULL;
  635. if (end - start > PY_SSIZE_T_MAX / (2+7+1))
  636. end = start + PY_SSIZE_T_MAX / (2+7+1);
  637. for (i = start, ressize = 0; i < end; ++i) {
  638. /* object is guaranteed to be "ready" */
  639. ch = PyUnicode_READ_CHAR(object, i);
  640. if (ch<10)
  641. ressize += 2+1+1;
  642. else if (ch<100)
  643. ressize += 2+2+1;
  644. else if (ch<1000)
  645. ressize += 2+3+1;
  646. else if (ch<10000)
  647. ressize += 2+4+1;
  648. else if (ch<100000)
  649. ressize += 2+5+1;
  650. else if (ch<1000000)
  651. ressize += 2+6+1;
  652. else
  653. ressize += 2+7+1;
  654. }
  655. /* allocate replacement */
  656. res = PyUnicode_New(ressize, 127);
  657. if (res == NULL) {
  658. Py_DECREF(object);
  659. return NULL;
  660. }
  661. outp = PyUnicode_1BYTE_DATA(res);
  662. /* generate replacement */
  663. for (i = start; i < end; ++i) {
  664. int digits;
  665. int base;
  666. ch = PyUnicode_READ_CHAR(object, i);
  667. *outp++ = '&';
  668. *outp++ = '#';
  669. if (ch<10) {
  670. digits = 1;
  671. base = 1;
  672. }
  673. else if (ch<100) {
  674. digits = 2;
  675. base = 10;
  676. }
  677. else if (ch<1000) {
  678. digits = 3;
  679. base = 100;
  680. }
  681. else if (ch<10000) {
  682. digits = 4;
  683. base = 1000;
  684. }
  685. else if (ch<100000) {
  686. digits = 5;
  687. base = 10000;
  688. }
  689. else if (ch<1000000) {
  690. digits = 6;
  691. base = 100000;
  692. }
  693. else {
  694. digits = 7;
  695. base = 1000000;
  696. }
  697. while (digits-->0) {
  698. *outp++ = '0' + ch/base;
  699. ch %= base;
  700. base /= 10;
  701. }
  702. *outp++ = ';';
  703. }
  704. assert(_PyUnicode_CheckConsistency(res, 1));
  705. restuple = Py_BuildValue("(Nn)", res, end);
  706. Py_DECREF(object);
  707. return restuple;
  708. }
  709. else {
  710. wrong_exception_type(exc);
  711. return NULL;
  712. }
  713. }
  714. PyObject *PyCodec_BackslashReplaceErrors(PyObject *exc)
  715. {
  716. PyObject *object;
  717. Py_ssize_t i;
  718. Py_ssize_t start;
  719. Py_ssize_t end;
  720. PyObject *res;
  721. Py_UCS1 *outp;
  722. int ressize;
  723. Py_UCS4 c;
  724. if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeDecodeError)) {
  725. const unsigned char *p;
  726. if (PyUnicodeDecodeError_GetStart(exc, &start))
  727. return NULL;
  728. if (PyUnicodeDecodeError_GetEnd(exc, &end))
  729. return NULL;
  730. if (!(object = PyUnicodeDecodeError_GetObject(exc)))
  731. return NULL;
  732. p = (const unsigned char*)PyBytes_AS_STRING(object);
  733. res = PyUnicode_New(4 * (end - start), 127);
  734. if (res == NULL) {
  735. Py_DECREF(object);
  736. return NULL;
  737. }
  738. outp = PyUnicode_1BYTE_DATA(res);
  739. for (i = start; i < end; i++, outp += 4) {
  740. unsigned char c = p[i];
  741. outp[0] = '\\';
  742. outp[1] = 'x';
  743. outp[2] = Py_hexdigits[(c>>4)&0xf];
  744. outp[3] = Py_hexdigits[c&0xf];
  745. }
  746. assert(_PyUnicode_CheckConsistency(res, 1));
  747. Py_DECREF(object);
  748. return Py_BuildValue("(Nn)", res, end);
  749. }
  750. if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeEncodeError)) {
  751. if (PyUnicodeEncodeError_GetStart(exc, &start))
  752. return NULL;
  753. if (PyUnicodeEncodeError_GetEnd(exc, &end))
  754. return NULL;
  755. if (!(object = PyUnicodeEncodeError_GetObject(exc)))
  756. return NULL;
  757. }
  758. else if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeTranslateError)) {
  759. if (PyUnicodeTranslateError_GetStart(exc, &start))
  760. return NULL;
  761. if (PyUnicodeTranslateError_GetEnd(exc, &end))
  762. return NULL;
  763. if (!(object = PyUnicodeTranslateError_GetObject(exc)))
  764. return NULL;
  765. }
  766. else {
  767. wrong_exception_type(exc);
  768. return NULL;
  769. }
  770. if (end - start > PY_SSIZE_T_MAX / (1+1+8))
  771. end = start + PY_SSIZE_T_MAX / (1+1+8);
  772. for (i = start, ressize = 0; i < end; ++i) {
  773. /* object is guaranteed to be "ready" */
  774. c = PyUnicode_READ_CHAR(object, i);
  775. if (c >= 0x10000) {
  776. ressize += 1+1+8;
  777. }
  778. else if (c >= 0x100) {
  779. ressize += 1+1+4;
  780. }
  781. else
  782. ressize += 1+1+2;
  783. }
  784. res = PyUnicode_New(ressize, 127);
  785. if (res == NULL) {
  786. Py_DECREF(object);
  787. return NULL;
  788. }
  789. outp = PyUnicode_1BYTE_DATA(res);
  790. for (i = start; i < end; ++i) {
  791. c = PyUnicode_READ_CHAR(object, i);
  792. *outp++ = '\\';
  793. if (c >= 0x00010000) {
  794. *outp++ = 'U';
  795. *outp++ = Py_hexdigits[(c>>28)&0xf];
  796. *outp++ = Py_hexdigits[(c>>24)&0xf];
  797. *outp++ = Py_hexdigits[(c>>20)&0xf];
  798. *outp++ = Py_hexdigits[(c>>16)&0xf];
  799. *outp++ = Py_hexdigits[(c>>12)&0xf];
  800. *outp++ = Py_hexdigits[(c>>8)&0xf];
  801. }
  802. else if (c >= 0x100) {
  803. *outp++ = 'u';
  804. *outp++ = Py_hexdigits[(c>>12)&0xf];
  805. *outp++ = Py_hexdigits[(c>>8)&0xf];
  806. }
  807. else
  808. *outp++ = 'x';
  809. *outp++ = Py_hexdigits[(c>>4)&0xf];
  810. *outp++ = Py_hexdigits[c&0xf];
  811. }
  812. assert(_PyUnicode_CheckConsistency(res, 1));
  813. Py_DECREF(object);
  814. return Py_BuildValue("(Nn)", res, end);
  815. }
  816. static _PyUnicode_Name_CAPI *ucnhash_capi = NULL;
  817. PyObject *PyCodec_NameReplaceErrors(PyObject *exc)
  818. {
  819. if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeEncodeError)) {
  820. PyObject *restuple;
  821. PyObject *object;
  822. Py_ssize_t i;
  823. Py_ssize_t start;
  824. Py_ssize_t end;
  825. PyObject *res;
  826. Py_UCS1 *outp;
  827. Py_ssize_t ressize;
  828. int replsize;
  829. Py_UCS4 c;
  830. char buffer[256]; /* NAME_MAXLEN */
  831. if (PyUnicodeEncodeError_GetStart(exc, &start))
  832. return NULL;
  833. if (PyUnicodeEncodeError_GetEnd(exc, &end))
  834. return NULL;
  835. if (!(object = PyUnicodeEncodeError_GetObject(exc)))
  836. return NULL;
  837. if (!ucnhash_capi) {
  838. /* load the unicode data module */
  839. ucnhash_capi = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
  840. PyUnicodeData_CAPSULE_NAME, 1);
  841. if (!ucnhash_capi) {
  842. return NULL;
  843. }
  844. }
  845. for (i = start, ressize = 0; i < end; ++i) {
  846. /* object is guaranteed to be "ready" */
  847. c = PyUnicode_READ_CHAR(object, i);
  848. if (ucnhash_capi->getname(c, buffer, sizeof(buffer), 1)) {
  849. replsize = 1+1+1+(int)strlen(buffer)+1;
  850. }
  851. else if (c >= 0x10000) {
  852. replsize = 1+1+8;
  853. }
  854. else if (c >= 0x100) {
  855. replsize = 1+1+4;
  856. }
  857. else
  858. replsize = 1+1+2;
  859. if (ressize > PY_SSIZE_T_MAX - replsize)
  860. break;
  861. ressize += replsize;
  862. }
  863. end = i;
  864. res = PyUnicode_New(ressize, 127);
  865. if (res==NULL)
  866. return NULL;
  867. for (i = start, outp = PyUnicode_1BYTE_DATA(res);
  868. i < end; ++i) {
  869. c = PyUnicode_READ_CHAR(object, i);
  870. *outp++ = '\\';
  871. if (ucnhash_capi->getname(c, buffer, sizeof(buffer), 1)) {
  872. *outp++ = 'N';
  873. *outp++ = '{';
  874. strcpy((char *)outp, buffer);
  875. outp += strlen(buffer);
  876. *outp++ = '}';
  877. continue;
  878. }
  879. if (c >= 0x00010000) {
  880. *outp++ = 'U';
  881. *outp++ = Py_hexdigits[(c>>28)&0xf];
  882. *outp++ = Py_hexdigits[(c>>24)&0xf];
  883. *outp++ = Py_hexdigits[(c>>20)&0xf];
  884. *outp++ = Py_hexdigits[(c>>16)&0xf];
  885. *outp++ = Py_hexdigits[(c>>12)&0xf];
  886. *outp++ = Py_hexdigits[(c>>8)&0xf];
  887. }
  888. else if (c >= 0x100) {
  889. *outp++ = 'u';
  890. *outp++ = Py_hexdigits[(c>>12)&0xf];
  891. *outp++ = Py_hexdigits[(c>>8)&0xf];
  892. }
  893. else
  894. *outp++ = 'x';
  895. *outp++ = Py_hexdigits[(c>>4)&0xf];
  896. *outp++ = Py_hexdigits[c&0xf];
  897. }
  898. assert(outp == PyUnicode_1BYTE_DATA(res) + ressize);
  899. assert(_PyUnicode_CheckConsistency(res, 1));
  900. restuple = Py_BuildValue("(Nn)", res, end);
  901. Py_DECREF(object);
  902. return restuple;
  903. }
  904. else {
  905. wrong_exception_type(exc);
  906. return NULL;
  907. }
  908. }
  909. #define ENC_UNKNOWN -1
  910. #define ENC_UTF8 0
  911. #define ENC_UTF16BE 1
  912. #define ENC_UTF16LE 2
  913. #define ENC_UTF32BE 3
  914. #define ENC_UTF32LE 4
  915. static int
  916. get_standard_encoding(const char *encoding, int *bytelength)
  917. {
  918. if (Py_TOLOWER(encoding[0]) == 'u' &&
  919. Py_TOLOWER(encoding[1]) == 't' &&
  920. Py_TOLOWER(encoding[2]) == 'f') {
  921. encoding += 3;
  922. if (*encoding == '-' || *encoding == '_' )
  923. encoding++;
  924. if (encoding[0] == '8' && encoding[1] == '\0') {
  925. *bytelength = 3;
  926. return ENC_UTF8;
  927. }
  928. else if (encoding[0] == '1' && encoding[1] == '6') {
  929. encoding += 2;
  930. *bytelength = 2;
  931. if (*encoding == '\0') {
  932. #ifdef WORDS_BIGENDIAN
  933. return ENC_UTF16BE;
  934. #else
  935. return ENC_UTF16LE;
  936. #endif
  937. }
  938. if (*encoding == '-' || *encoding == '_' )
  939. encoding++;
  940. if (Py_TOLOWER(encoding[1]) == 'e' && encoding[2] == '\0') {
  941. if (Py_TOLOWER(encoding[0]) == 'b')
  942. return ENC_UTF16BE;
  943. if (Py_TOLOWER(encoding[0]) == 'l')
  944. return ENC_UTF16LE;
  945. }
  946. }
  947. else if (encoding[0] == '3' && encoding[1] == '2') {
  948. encoding += 2;
  949. *bytelength = 4;
  950. if (*encoding == '\0') {
  951. #ifdef WORDS_BIGENDIAN
  952. return ENC_UTF32BE;
  953. #else
  954. return ENC_UTF32LE;
  955. #endif
  956. }
  957. if (*encoding == '-' || *encoding == '_' )
  958. encoding++;
  959. if (Py_TOLOWER(encoding[1]) == 'e' && encoding[2] == '\0') {
  960. if (Py_TOLOWER(encoding[0]) == 'b')
  961. return ENC_UTF32BE;
  962. if (Py_TOLOWER(encoding[0]) == 'l')
  963. return ENC_UTF32LE;
  964. }
  965. }
  966. }
  967. else if (strcmp(encoding, "CP_UTF8") == 0) {
  968. *bytelength = 3;
  969. return ENC_UTF8;
  970. }
  971. return ENC_UNKNOWN;
  972. }
  973. /* This handler is declared static until someone demonstrates
  974. a need to call it directly. */
  975. static PyObject *
  976. PyCodec_SurrogatePassErrors(PyObject *exc)
  977. {
  978. PyObject *restuple;
  979. PyObject *object;
  980. PyObject *encode;
  981. const char *encoding;
  982. int code;
  983. int bytelength;
  984. Py_ssize_t i;
  985. Py_ssize_t start;
  986. Py_ssize_t end;
  987. PyObject *res;
  988. if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeEncodeError)) {
  989. unsigned char *outp;
  990. if (PyUnicodeEncodeError_GetStart(exc, &start))
  991. return NULL;
  992. if (PyUnicodeEncodeError_GetEnd(exc, &end))
  993. return NULL;
  994. if (!(object = PyUnicodeEncodeError_GetObject(exc)))
  995. return NULL;
  996. if (!(encode = PyUnicodeEncodeError_GetEncoding(exc))) {
  997. Py_DECREF(object);
  998. return NULL;
  999. }
  1000. if (!(encoding = PyUnicode_AsUTF8(encode))) {
  1001. Py_DECREF(object);
  1002. Py_DECREF(encode);
  1003. return NULL;
  1004. }
  1005. code = get_standard_encoding(encoding, &bytelength);
  1006. Py_DECREF(encode);
  1007. if (code == ENC_UNKNOWN) {
  1008. /* Not supported, fail with original exception */
  1009. PyErr_SetObject(PyExceptionInstance_Class(exc), exc);
  1010. Py_DECREF(object);
  1011. return NULL;
  1012. }
  1013. if (end - start > PY_SSIZE_T_MAX / bytelength)
  1014. end = start + PY_SSIZE_T_MAX / bytelength;
  1015. res = PyBytes_FromStringAndSize(NULL, bytelength*(end-start));
  1016. if (!res) {
  1017. Py_DECREF(object);
  1018. return NULL;
  1019. }
  1020. outp = (unsigned char*)PyBytes_AsString(res);
  1021. for (i = start; i < end; i++) {
  1022. /* object is guaranteed to be "ready" */
  1023. Py_UCS4 ch = PyUnicode_READ_CHAR(object, i);
  1024. if (!Py_UNICODE_IS_SURROGATE(ch)) {
  1025. /* Not a surrogate, fail with original exception */
  1026. PyErr_SetObject(PyExceptionInstance_Class(exc), exc);
  1027. Py_DECREF(res);
  1028. Py_DECREF(object);
  1029. return NULL;
  1030. }
  1031. switch (code) {
  1032. case ENC_UTF8:
  1033. *outp++ = (unsigned char)(0xe0 | (ch >> 12));
  1034. *outp++ = (unsigned char)(0x80 | ((ch >> 6) & 0x3f));
  1035. *outp++ = (unsigned char)(0x80 | (ch & 0x3f));
  1036. break;
  1037. case ENC_UTF16LE:
  1038. *outp++ = (unsigned char) ch;
  1039. *outp++ = (unsigned char)(ch >> 8);
  1040. break;
  1041. case ENC_UTF16BE:
  1042. *outp++ = (unsigned char)(ch >> 8);
  1043. *outp++ = (unsigned char) ch;
  1044. break;
  1045. case ENC_UTF32LE:
  1046. *outp++ = (unsigned char) ch;
  1047. *outp++ = (unsigned char)(ch >> 8);
  1048. *outp++ = (unsigned char)(ch >> 16);
  1049. *outp++ = (unsigned char)(ch >> 24);
  1050. break;
  1051. case ENC_UTF32BE:
  1052. *outp++ = (unsigned char)(ch >> 24);
  1053. *outp++ = (unsigned char)(ch >> 16);
  1054. *outp++ = (unsigned char)(ch >> 8);
  1055. *outp++ = (unsigned char) ch;
  1056. break;
  1057. }
  1058. }
  1059. restuple = Py_BuildValue("(On)", res, end);
  1060. Py_DECREF(res);
  1061. Py_DECREF(object);
  1062. return restuple;
  1063. }
  1064. else if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeDecodeError)) {
  1065. const unsigned char *p;
  1066. Py_UCS4 ch = 0;
  1067. if (PyUnicodeDecodeError_GetStart(exc, &start))
  1068. return NULL;
  1069. if (PyUnicodeDecodeError_GetEnd(exc, &end))
  1070. return NULL;
  1071. if (!(object = PyUnicodeDecodeError_GetObject(exc)))
  1072. return NULL;
  1073. p = (const unsigned char*)PyBytes_AS_STRING(object);
  1074. if (!(encode = PyUnicodeDecodeError_GetEncoding(exc))) {
  1075. Py_DECREF(object);
  1076. return NULL;
  1077. }
  1078. if (!(encoding = PyUnicode_AsUTF8(encode))) {
  1079. Py_DECREF(object);
  1080. Py_DECREF(encode);
  1081. return NULL;
  1082. }
  1083. code = get_standard_encoding(encoding, &bytelength);
  1084. Py_DECREF(encode);
  1085. if (code == ENC_UNKNOWN) {
  1086. /* Not supported, fail with original exception */
  1087. PyErr_SetObject(PyExceptionInstance_Class(exc), exc);
  1088. Py_DECREF(object);
  1089. return NULL;
  1090. }
  1091. /* Try decoding a single surrogate character. If
  1092. there are more, let the codec call us again. */
  1093. p += start;
  1094. if (PyBytes_GET_SIZE(object) - start >= bytelength) {
  1095. switch (code) {
  1096. case ENC_UTF8:
  1097. if ((p[0] & 0xf0) == 0xe0 &&
  1098. (p[1] & 0xc0) == 0x80 &&
  1099. (p[2] & 0xc0) == 0x80) {
  1100. /* it's a three-byte code */
  1101. ch = ((p[0] & 0x0f) << 12) + ((p[1] & 0x3f) << 6) + (p[2] & 0x3f);
  1102. }
  1103. break;
  1104. case ENC_UTF16LE:
  1105. ch = p[1] << 8 | p[0];
  1106. break;
  1107. case ENC_UTF16BE:
  1108. ch = p[0] << 8 | p[1];
  1109. break;
  1110. case ENC_UTF32LE:
  1111. ch = (p[3] << 24) | (p[2] << 16) | (p[1] << 8) | p[0];
  1112. break;
  1113. case ENC_UTF32BE:
  1114. ch = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
  1115. break;
  1116. }
  1117. }
  1118. Py_DECREF(object);
  1119. if (!Py_UNICODE_IS_SURROGATE(ch)) {
  1120. /* it's not a surrogate - fail */
  1121. PyErr_SetObject(PyExceptionInstance_Class(exc), exc);
  1122. return NULL;
  1123. }
  1124. res = PyUnicode_FromOrdinal(ch);
  1125. if (res == NULL)
  1126. return NULL;
  1127. return Py_BuildValue("(Nn)", res, start + bytelength);
  1128. }
  1129. else {
  1130. wrong_exception_type(exc);
  1131. return NULL;
  1132. }
  1133. }
  1134. static PyObject *
  1135. PyCodec_SurrogateEscapeErrors(PyObject *exc)
  1136. {
  1137. PyObject *restuple;
  1138. PyObject *object;
  1139. Py_ssize_t i;
  1140. Py_ssize_t start;
  1141. Py_ssize_t end;
  1142. PyObject *res;
  1143. if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeEncodeError)) {
  1144. char *outp;
  1145. if (PyUnicodeEncodeError_GetStart(exc, &start))
  1146. return NULL;
  1147. if (PyUnicodeEncodeError_GetEnd(exc, &end))
  1148. return NULL;
  1149. if (!(object = PyUnicodeEncodeError_GetObject(exc)))
  1150. return NULL;
  1151. res = PyBytes_FromStringAndSize(NULL, end-start);
  1152. if (!res) {
  1153. Py_DECREF(object);
  1154. return NULL;
  1155. }
  1156. outp = PyBytes_AsString(res);
  1157. for (i = start; i < end; i++) {
  1158. /* object is guaranteed to be "ready" */
  1159. Py_UCS4 ch = PyUnicode_READ_CHAR(object, i);
  1160. if (ch < 0xdc80 || ch > 0xdcff) {
  1161. /* Not a UTF-8b surrogate, fail with original exception */
  1162. PyErr_SetObject(PyExceptionInstance_Class(exc), exc);
  1163. Py_DECREF(res);
  1164. Py_DECREF(object);
  1165. return NULL;
  1166. }
  1167. *outp++ = ch - 0xdc00;
  1168. }
  1169. restuple = Py_BuildValue("(On)", res, end);
  1170. Py_DECREF(res);
  1171. Py_DECREF(object);
  1172. return restuple;
  1173. }
  1174. else if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeDecodeError)) {
  1175. PyObject *str;
  1176. const unsigned char *p;
  1177. Py_UCS2 ch[4]; /* decode up to 4 bad bytes. */
  1178. int consumed = 0;
  1179. if (PyUnicodeDecodeError_GetStart(exc, &start))
  1180. return NULL;
  1181. if (PyUnicodeDecodeError_GetEnd(exc, &end))
  1182. return NULL;
  1183. if (!(object = PyUnicodeDecodeError_GetObject(exc)))
  1184. return NULL;
  1185. p = (const unsigned char*)PyBytes_AS_STRING(object);
  1186. while (consumed < 4 && consumed < end-start) {
  1187. /* Refuse to escape ASCII bytes. */
  1188. if (p[start+consumed] < 128)
  1189. break;
  1190. ch[consumed] = 0xdc00 + p[start+consumed];
  1191. consumed++;
  1192. }
  1193. Py_DECREF(object);
  1194. if (!consumed) {
  1195. /* codec complained about ASCII byte. */
  1196. PyErr_SetObject(PyExceptionInstance_Class(exc), exc);
  1197. return NULL;
  1198. }
  1199. str = PyUnicode_FromKindAndData(PyUnicode_2BYTE_KIND, ch, consumed);
  1200. if (str == NULL)
  1201. return NULL;
  1202. return Py_BuildValue("(Nn)", str, start+consumed);
  1203. }
  1204. else {
  1205. wrong_exception_type(exc);
  1206. return NULL;
  1207. }
  1208. }
  1209. static PyObject *strict_errors(PyObject *self, PyObject *exc)
  1210. {
  1211. return PyCodec_StrictErrors(exc);
  1212. }
  1213. static PyObject *ignore_errors(PyObject *self, PyObject *exc)
  1214. {
  1215. return PyCodec_IgnoreErrors(exc);
  1216. }
  1217. static PyObject *replace_errors(PyObject *self, PyObject *exc)
  1218. {
  1219. return PyCodec_ReplaceErrors(exc);
  1220. }
  1221. static PyObject *xmlcharrefreplace_errors(PyObject *self, PyObject *exc)
  1222. {
  1223. return PyCodec_XMLCharRefReplaceErrors(exc);
  1224. }
  1225. static PyObject *backslashreplace_errors(PyObject *self, PyObject *exc)
  1226. {
  1227. return PyCodec_BackslashReplaceErrors(exc);
  1228. }
  1229. static PyObject *namereplace_errors(PyObject *self, PyObject *exc)
  1230. {
  1231. return PyCodec_NameReplaceErrors(exc);
  1232. }
  1233. static PyObject *surrogatepass_errors(PyObject *self, PyObject *exc)
  1234. {
  1235. return PyCodec_SurrogatePassErrors(exc);
  1236. }
  1237. static PyObject *surrogateescape_errors(PyObject *self, PyObject *exc)
  1238. {
  1239. return PyCodec_SurrogateEscapeErrors(exc);
  1240. }
  1241. static int _PyCodecRegistry_Init(void)
  1242. {
  1243. static struct {
  1244. const char *name;
  1245. PyMethodDef def;
  1246. } methods[] =
  1247. {
  1248. {
  1249. "strict",
  1250. {
  1251. "strict_errors",
  1252. strict_errors,
  1253. METH_O,
  1254. PyDoc_STR("Implements the 'strict' error handling, which "
  1255. "raises a UnicodeError on coding errors.")
  1256. }
  1257. },
  1258. {
  1259. "ignore",
  1260. {
  1261. "ignore_errors",
  1262. ignore_errors,
  1263. METH_O,
  1264. PyDoc_STR("Implements the 'ignore' error handling, which "
  1265. "ignores malformed data and continues.")
  1266. }
  1267. },
  1268. {
  1269. "replace",
  1270. {
  1271. "replace_errors",
  1272. replace_errors,
  1273. METH_O,
  1274. PyDoc_STR("Implements the 'replace' error handling, which "
  1275. "replaces malformed data with a replacement marker.")
  1276. }
  1277. },
  1278. {
  1279. "xmlcharrefreplace",
  1280. {
  1281. "xmlcharrefreplace_errors",
  1282. xmlcharrefreplace_errors,
  1283. METH_O,
  1284. PyDoc_STR("Implements the 'xmlcharrefreplace' error handling, "
  1285. "which replaces an unencodable character with the "
  1286. "appropriate XML character reference.")
  1287. }
  1288. },
  1289. {
  1290. "backslashreplace",
  1291. {
  1292. "backslashreplace_errors",
  1293. backslashreplace_errors,
  1294. METH_O,
  1295. PyDoc_STR("Implements the 'backslashreplace' error handling, "
  1296. "which replaces malformed data with a backslashed "
  1297. "escape sequence.")
  1298. }
  1299. },
  1300. {
  1301. "namereplace",
  1302. {
  1303. "namereplace_errors",
  1304. namereplace_errors,
  1305. METH_O,
  1306. PyDoc_STR("Implements the 'namereplace' error handling, "
  1307. "which replaces an unencodable character with a "
  1308. "\\N{...} escape sequence.")
  1309. }
  1310. },
  1311. {
  1312. "surrogatepass",
  1313. {
  1314. "surrogatepass",
  1315. surrogatepass_errors,
  1316. METH_O
  1317. }
  1318. },
  1319. {
  1320. "surrogateescape",
  1321. {
  1322. "surrogateescape",
  1323. surrogateescape_errors,
  1324. METH_O
  1325. }
  1326. }
  1327. };
  1328. PyInterpreterState *interp = _PyInterpreterState_GET();
  1329. PyObject *mod;
  1330. if (interp->codec_search_path != NULL)
  1331. return 0;
  1332. interp->codec_search_path = PyList_New(0);
  1333. if (interp->codec_search_path == NULL) {
  1334. return -1;
  1335. }
  1336. interp->codec_search_cache = PyDict_New();
  1337. if (interp->codec_search_cache == NULL) {
  1338. return -1;
  1339. }
  1340. interp->codec_error_registry = PyDict_New();
  1341. if (interp->codec_error_registry == NULL) {
  1342. return -1;
  1343. }
  1344. for (size_t i = 0; i < Py_ARRAY_LENGTH(methods); ++i) {
  1345. PyObject *func = PyCFunction_NewEx(&methods[i].def, NULL, NULL);
  1346. if (!func) {
  1347. return -1;
  1348. }
  1349. int res = PyCodec_RegisterError(methods[i].name, func);
  1350. Py_DECREF(func);
  1351. if (res) {
  1352. return -1;
  1353. }
  1354. }
  1355. mod = PyImport_ImportModule("encodings");
  1356. if (mod == NULL) {
  1357. return -1;
  1358. }
  1359. Py_DECREF(mod);
  1360. interp->codecs_initialized = 1;
  1361. return 0;
  1362. }