blob: a0a540304aa9b1ae521f30205728391ced889f32 [file] [log] [blame]
Guido van Rossumfeee4b92000-03-10 22:57:27 +00001/* ------------------------------------------------------------------------
2
3 Python Codec Registry and support functions
4
5Written by Marc-Andre Lemburg (mal@lemburg.com).
6
Guido van Rossum16b1ad92000-08-03 16:24:25 +00007Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumfeee4b92000-03-10 22:57:27 +00008
9 ------------------------------------------------------------------------ */
10
11#include "Python.h"
Serhiy Storchaka166ebc42014-11-25 13:57:17 +020012#include "ucnhash.h"
Guido van Rossumfeee4b92000-03-10 22:57:27 +000013#include <ctype.h>
14
Victor Stinnerf5cff562011-10-14 02:13:11 +020015const char *Py_hexdigits = "0123456789abcdef";
16
Guido van Rossumfeee4b92000-03-10 22:57:27 +000017/* --- Codec Registry ----------------------------------------------------- */
18
19/* Import the standard encodings package which will register the first
Guido van Rossum98297ee2007-11-06 21:34:58 +000020 codec search function.
Guido van Rossumfeee4b92000-03-10 22:57:27 +000021
22 This is done in a lazy way so that the Unicode implementation does
23 not downgrade startup time of scripts not needing it.
24
Guido van Rossumb95de4f2000-03-31 17:25:23 +000025 ImportErrors are silently ignored by this function. Only one try is
26 made.
Guido van Rossumfeee4b92000-03-10 22:57:27 +000027
28*/
29
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +000030static int _PyCodecRegistry_Init(void); /* Forward */
Guido van Rossumfeee4b92000-03-10 22:57:27 +000031
Guido van Rossumfeee4b92000-03-10 22:57:27 +000032int PyCodec_Register(PyObject *search_function)
33{
Nicholas Bastine5662ae2004-03-24 22:22:12 +000034 PyInterpreterState *interp = PyThreadState_GET()->interp;
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +000035 if (interp->codec_search_path == NULL && _PyCodecRegistry_Init())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000036 goto onError;
Guido van Rossumfeee4b92000-03-10 22:57:27 +000037 if (search_function == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000038 PyErr_BadArgument();
39 goto onError;
Guido van Rossumfeee4b92000-03-10 22:57:27 +000040 }
41 if (!PyCallable_Check(search_function)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 PyErr_SetString(PyExc_TypeError, "argument must be callable");
43 goto onError;
Guido van Rossumfeee4b92000-03-10 22:57:27 +000044 }
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +000045 return PyList_Append(interp->codec_search_path, search_function);
Guido van Rossumb95de4f2000-03-31 17:25:23 +000046
47 onError:
48 return -1;
Guido van Rossumfeee4b92000-03-10 22:57:27 +000049}
50
Guido van Rossum9e896b32000-04-05 20:11:21 +000051/* Convert a string to a normalized Python string: all characters are
52 converted to lower case, spaces are replaced with underscores. */
53
Guido van Rossumfeee4b92000-03-10 22:57:27 +000054static
Guido van Rossum9e896b32000-04-05 20:11:21 +000055PyObject *normalizestring(const char *string)
Guido van Rossumfeee4b92000-03-10 22:57:27 +000056{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020057 size_t i;
Guido van Rossum582acec2000-06-28 22:07:35 +000058 size_t len = strlen(string);
Guido van Rossumfeee4b92000-03-10 22:57:27 +000059 char *p;
60 PyObject *v;
Guido van Rossum21431e82007-10-19 21:48:41 +000061
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000062 if (len > PY_SSIZE_T_MAX) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 PyErr_SetString(PyExc_OverflowError, "string is too large");
64 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000065 }
Guido van Rossum21431e82007-10-19 21:48:41 +000066
67 p = PyMem_Malloc(len + 1);
68 if (p == NULL)
Victor Stinnercc351592013-07-12 00:02:55 +020069 return PyErr_NoMemory();
Guido van Rossum9e896b32000-04-05 20:11:21 +000070 for (i = 0; i < len; i++) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020071 char ch = string[i];
Guido van Rossum9e896b32000-04-05 20:11:21 +000072 if (ch == ' ')
73 ch = '-';
74 else
Antoine Pitroucf9d3c02011-07-24 02:27:04 +020075 ch = Py_TOLOWER(Py_CHARMASK(ch));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076 p[i] = ch;
Guido van Rossum9e896b32000-04-05 20:11:21 +000077 }
Guido van Rossum21431e82007-10-19 21:48:41 +000078 p[i] = '\0';
79 v = PyUnicode_FromString(p);
80 if (v == NULL)
81 return NULL;
82 PyMem_Free(p);
Guido van Rossumfeee4b92000-03-10 22:57:27 +000083 return v;
84}
85
86/* Lookup the given encoding and return a tuple providing the codec
87 facilities.
88
89 The encoding string is looked up converted to all lower-case
90 characters. This makes encodings looked up through this mechanism
91 effectively case-insensitive.
92
Guido van Rossum98297ee2007-11-06 21:34:58 +000093 If no codec is found, a LookupError is set and NULL returned.
Guido van Rossumb95de4f2000-03-31 17:25:23 +000094
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*/
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000100
101PyObject *_PyCodec_Lookup(const char *encoding)
102{
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000103 PyInterpreterState *interp;
Guido van Rossum5ba3c842000-03-24 20:52:23 +0000104 PyObject *result, *args = NULL, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000105 Py_ssize_t i, len;
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000106
Fred Drake766de832000-05-09 19:55:59 +0000107 if (encoding == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 PyErr_BadArgument();
109 goto onError;
Fred Drake766de832000-05-09 19:55:59 +0000110 }
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000111
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000112 interp = PyThreadState_GET()->interp;
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000113 if (interp->codec_search_path == NULL && _PyCodecRegistry_Init())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 goto onError;
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000115
Guido van Rossum9e896b32000-04-05 20:11:21 +0000116 /* Convert the encoding to a normalized Python string: all
Thomas Wouters7e474022000-07-16 12:04:32 +0000117 characters are converted to lower case, spaces and hyphens are
Guido van Rossum9e896b32000-04-05 20:11:21 +0000118 replaced with underscores. */
119 v = normalizestring(encoding);
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000120 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 goto onError;
Guido van Rossum21431e82007-10-19 21:48:41 +0000122 PyUnicode_InternInPlace(&v);
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000123
124 /* First, try to lookup the name in the registry dictionary */
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000125 result = PyDict_GetItem(interp->codec_search_cache, v);
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000126 if (result != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 Py_INCREF(result);
128 Py_DECREF(v);
129 return result;
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000130 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000131
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000132 /* Next, scan the search functions in order of registration */
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000133 args = PyTuple_New(1);
134 if (args == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 goto onError;
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000136 PyTuple_SET_ITEM(args,0,v);
Guido van Rossum5ba3c842000-03-24 20:52:23 +0000137
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000138 len = PyList_Size(interp->codec_search_path);
Guido van Rossum5ba3c842000-03-24 20:52:23 +0000139 if (len < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 goto onError;
Guido van Rossumb95de4f2000-03-31 17:25:23 +0000141 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 PyErr_SetString(PyExc_LookupError,
143 "no codec search functions registered: "
144 "can't find encoding");
145 goto onError;
Guido van Rossumb95de4f2000-03-31 17:25:23 +0000146 }
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000147
148 for (i = 0; i < len; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 PyObject *func;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 func = PyList_GetItem(interp->codec_search_path, i);
152 if (func == NULL)
153 goto onError;
154 result = PyEval_CallObject(func, args);
155 if (result == NULL)
156 goto onError;
157 if (result == Py_None) {
158 Py_DECREF(result);
159 continue;
160 }
161 if (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 4) {
162 PyErr_SetString(PyExc_TypeError,
163 "codec search functions must return 4-tuples");
164 Py_DECREF(result);
165 goto onError;
166 }
167 break;
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000168 }
169 if (i == len) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 /* XXX Perhaps we should cache misses too ? */
171 PyErr_Format(PyExc_LookupError,
Martin v. Löwiseb42b022002-09-26 16:01:24 +0000172 "unknown encoding: %s", encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 goto onError;
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000174 }
175
176 /* Cache and return the result */
Neal Norwitz9edcc2e2007-08-11 04:58:26 +0000177 if (PyDict_SetItem(interp->codec_search_cache, v, result) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 Py_DECREF(result);
179 goto onError;
Neal Norwitz9edcc2e2007-08-11 04:58:26 +0000180 }
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000181 Py_DECREF(args);
182 return result;
183
184 onError:
185 Py_XDECREF(args);
186 return NULL;
187}
188
Nick Coghlan8fad1672014-09-15 23:50:44 +1200189int _PyCodec_Forget(const char *encoding)
190{
191 PyInterpreterState *interp;
192 PyObject *v;
193 int result;
194
195 interp = PyThreadState_GET()->interp;
196 if (interp->codec_search_path == NULL) {
197 return -1;
198 }
199
200 /* Convert the encoding to a normalized Python string: all
201 characters are converted to lower case, spaces and hyphens are
202 replaced with underscores. */
203 v = normalizestring(encoding);
204 if (v == NULL) {
205 return -1;
206 }
207
208 /* Drop the named codec from the internal cache */
209 result = PyDict_DelItem(interp->codec_search_cache, v);
210 Py_DECREF(v);
211
212 return result;
213}
214
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000215/* Codec registry encoding check API. */
216
217int PyCodec_KnownEncoding(const char *encoding)
218{
219 PyObject *codecs;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000221 codecs = _PyCodec_Lookup(encoding);
222 if (!codecs) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 PyErr_Clear();
224 return 0;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000225 }
226 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 Py_DECREF(codecs);
228 return 1;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000229 }
230}
231
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000232static
233PyObject *args_tuple(PyObject *object,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 const char *errors)
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000235{
236 PyObject *args;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000237
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000238 args = PyTuple_New(1 + (errors != NULL));
239 if (args == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 return NULL;
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000241 Py_INCREF(object);
242 PyTuple_SET_ITEM(args,0,object);
243 if (errors) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 PyObject *v;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 v = PyUnicode_FromString(errors);
247 if (v == NULL) {
248 Py_DECREF(args);
249 return NULL;
250 }
251 PyTuple_SET_ITEM(args, 1, v);
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000252 }
253 return args;
254}
255
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000256/* Helper function to get a codec item */
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000257
258static
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000259PyObject *codec_getitem(const char *encoding, int index)
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000260{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000261 PyObject *codecs;
262 PyObject *v;
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000263
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000264 codecs = _PyCodec_Lookup(encoding);
265 if (codecs == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000267 v = PyTuple_GET_ITEM(codecs, index);
268 Py_DECREF(codecs);
269 Py_INCREF(v);
270 return v;
271}
272
Nick Coghlana9b15242014-02-04 22:11:18 +1000273/* Helper functions to create an incremental codec. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000274static
Nick Coghlana9b15242014-02-04 22:11:18 +1000275PyObject *codec_makeincrementalcodec(PyObject *codec_info,
276 const char *errors,
277 const char *attrname)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000278{
Nick Coghlana9b15242014-02-04 22:11:18 +1000279 PyObject *ret, *inccodec;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000280
Nick Coghlana9b15242014-02-04 22:11:18 +1000281 inccodec = PyObject_GetAttrString(codec_info, attrname);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000282 if (inccodec == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000284 if (errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 ret = PyObject_CallFunction(inccodec, "s", errors);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000286 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 ret = PyObject_CallFunction(inccodec, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000288 Py_DECREF(inccodec);
289 return ret;
290}
291
Nick Coghlana9b15242014-02-04 22:11:18 +1000292static
293PyObject *codec_getincrementalcodec(const char *encoding,
294 const char *errors,
295 const char *attrname)
296{
297 PyObject *codec_info, *ret;
298
299 codec_info = _PyCodec_Lookup(encoding);
300 if (codec_info == NULL)
301 return NULL;
302 ret = codec_makeincrementalcodec(codec_info, errors, attrname);
303 Py_DECREF(codec_info);
304 return ret;
305}
306
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000307/* Helper function to create a stream codec. */
308
309static
310PyObject *codec_getstreamcodec(const char *encoding,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 PyObject *stream,
312 const char *errors,
313 const int index)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000314{
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000315 PyObject *codecs, *streamcodec, *codeccls;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000316
317 codecs = _PyCodec_Lookup(encoding);
318 if (codecs == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000320
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000321 codeccls = PyTuple_GET_ITEM(codecs, index);
322 if (errors != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 streamcodec = PyObject_CallFunction(codeccls, "Os", stream, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000324 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 streamcodec = PyObject_CallFunction(codeccls, "O", stream);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000326 Py_DECREF(codecs);
327 return streamcodec;
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000328}
329
Nick Coghlana9b15242014-02-04 22:11:18 +1000330/* Helpers to work with the result of _PyCodec_Lookup
331
332 */
333PyObject *_PyCodecInfo_GetIncrementalDecoder(PyObject *codec_info,
334 const char *errors)
335{
336 return codec_makeincrementalcodec(codec_info, errors,
337 "incrementaldecoder");
338}
339
340PyObject *_PyCodecInfo_GetIncrementalEncoder(PyObject *codec_info,
341 const char *errors)
342{
343 return codec_makeincrementalcodec(codec_info, errors,
344 "incrementalencoder");
345}
346
347
Guido van Rossum98297ee2007-11-06 21:34:58 +0000348/* Convenience APIs to query the Codec registry.
349
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000350 All APIs return a codec object with incremented refcount.
Guido van Rossum98297ee2007-11-06 21:34:58 +0000351
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000352 */
353
354PyObject *PyCodec_Encoder(const char *encoding)
355{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000356 return codec_getitem(encoding, 0);
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000357}
358
359PyObject *PyCodec_Decoder(const char *encoding)
360{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000361 return codec_getitem(encoding, 1);
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000362}
363
Thomas Woutersa9773292006-04-21 09:43:23 +0000364PyObject *PyCodec_IncrementalEncoder(const char *encoding,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 const char *errors)
Thomas Woutersa9773292006-04-21 09:43:23 +0000366{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000367 return codec_getincrementalcodec(encoding, errors, "incrementalencoder");
Thomas Woutersa9773292006-04-21 09:43:23 +0000368}
369
370PyObject *PyCodec_IncrementalDecoder(const char *encoding,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 const char *errors)
Thomas Woutersa9773292006-04-21 09:43:23 +0000372{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000373 return codec_getincrementalcodec(encoding, errors, "incrementaldecoder");
Thomas Woutersa9773292006-04-21 09:43:23 +0000374}
375
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000376PyObject *PyCodec_StreamReader(const char *encoding,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 PyObject *stream,
378 const char *errors)
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000379{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000380 return codec_getstreamcodec(encoding, stream, errors, 2);
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000381}
382
383PyObject *PyCodec_StreamWriter(const char *encoding,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 PyObject *stream,
385 const char *errors)
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000386{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000387 return codec_getstreamcodec(encoding, stream, errors, 3);
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000388}
389
Nick Coghlan8b097b42013-11-13 23:49:21 +1000390/* Helper that tries to ensure the reported exception chain indicates the
391 * codec that was invoked to trigger the failure without changing the type
392 * of the exception raised.
393 */
394static void
395wrap_codec_error(const char *operation,
396 const char *encoding)
397{
398 /* TrySetFromCause will replace the active exception with a suitably
399 * updated clone if it can, otherwise it will leave the original
400 * exception alone.
401 */
402 _PyErr_TrySetFromCause("%s with '%s' codec failed",
403 operation, encoding);
404}
405
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000406/* Encode an object (e.g. an Unicode object) using the given encoding
407 and return the resulting encoded object (usually a Python string).
408
409 errors is passed to the encoder factory as argument if non-NULL. */
410
Nick Coghlanc72e4e62013-11-22 22:39:36 +1000411static PyObject *
412_PyCodec_EncodeInternal(PyObject *object,
413 PyObject *encoder,
414 const char *encoding,
415 const char *errors)
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000416{
Neal Norwitz3715c3e2005-11-24 22:09:18 +0000417 PyObject *args = NULL, *result = NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000418 PyObject *v = NULL;
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000419
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000420 args = args_tuple(object, errors);
421 if (args == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000423
424 result = PyEval_CallObject(encoder, args);
Nick Coghlanc4c25802013-11-15 21:47:37 +1000425 if (result == NULL) {
426 wrap_codec_error("encoding", encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 goto onError;
Nick Coghlanc4c25802013-11-15 21:47:37 +1000428 }
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000429
Guido van Rossum98297ee2007-11-06 21:34:58 +0000430 if (!PyTuple_Check(result) ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 PyTuple_GET_SIZE(result) != 2) {
432 PyErr_SetString(PyExc_TypeError,
433 "encoder must return a tuple (object, integer)");
434 goto onError;
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000435 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000436 v = PyTuple_GET_ITEM(result,0);
437 Py_INCREF(v);
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000438 /* We don't check or use the second (integer) entry. */
439
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000440 Py_DECREF(args);
441 Py_DECREF(encoder);
442 Py_DECREF(result);
443 return v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000445 onError:
Neal Norwitz3715c3e2005-11-24 22:09:18 +0000446 Py_XDECREF(result);
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000447 Py_XDECREF(args);
448 Py_XDECREF(encoder);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000449 return NULL;
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000450}
451
452/* Decode an object (usually a Python string) using the given encoding
453 and return an equivalent object (e.g. an Unicode object).
454
455 errors is passed to the decoder factory as argument if non-NULL. */
456
Nick Coghlanc72e4e62013-11-22 22:39:36 +1000457static PyObject *
458_PyCodec_DecodeInternal(PyObject *object,
459 PyObject *decoder,
460 const char *encoding,
461 const char *errors)
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000462{
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000463 PyObject *args = NULL, *result = NULL;
464 PyObject *v;
465
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000466 args = args_tuple(object, errors);
467 if (args == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000469
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000470 result = PyEval_CallObject(decoder,args);
Nick Coghlanc4c25802013-11-15 21:47:37 +1000471 if (result == NULL) {
472 wrap_codec_error("decoding", encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 goto onError;
Nick Coghlanc4c25802013-11-15 21:47:37 +1000474 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000475 if (!PyTuple_Check(result) ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 PyTuple_GET_SIZE(result) != 2) {
477 PyErr_SetString(PyExc_TypeError,
478 "decoder must return a tuple (object,integer)");
479 goto onError;
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000480 }
481 v = PyTuple_GET_ITEM(result,0);
482 Py_INCREF(v);
483 /* We don't check or use the second (integer) entry. */
484
485 Py_DECREF(args);
486 Py_DECREF(decoder);
487 Py_DECREF(result);
488 return v;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000489
Guido van Rossumfeee4b92000-03-10 22:57:27 +0000490 onError:
491 Py_XDECREF(args);
492 Py_XDECREF(decoder);
493 Py_XDECREF(result);
494 return NULL;
495}
496
Nick Coghlanc72e4e62013-11-22 22:39:36 +1000497/* Generic encoding/decoding API */
498PyObject *PyCodec_Encode(PyObject *object,
499 const char *encoding,
500 const char *errors)
501{
502 PyObject *encoder;
503
504 encoder = PyCodec_Encoder(encoding);
505 if (encoder == NULL)
506 return NULL;
507
508 return _PyCodec_EncodeInternal(object, encoder, encoding, errors);
509}
510
511PyObject *PyCodec_Decode(PyObject *object,
512 const char *encoding,
513 const char *errors)
514{
515 PyObject *decoder;
516
517 decoder = PyCodec_Decoder(encoding);
518 if (decoder == NULL)
519 return NULL;
520
521 return _PyCodec_DecodeInternal(object, decoder, encoding, errors);
522}
523
524/* Text encoding/decoding API */
Nick Coghlana9b15242014-02-04 22:11:18 +1000525PyObject * _PyCodec_LookupTextEncoding(const char *encoding,
526 const char *alternate_command)
Nick Coghlanc72e4e62013-11-22 22:39:36 +1000527{
528 _Py_IDENTIFIER(_is_text_encoding);
529 PyObject *codec;
530 PyObject *attr;
Nick Coghlanc72e4e62013-11-22 22:39:36 +1000531 int is_text_codec;
532
533 codec = _PyCodec_Lookup(encoding);
534 if (codec == NULL)
535 return NULL;
536
537 /* Backwards compatibility: assume any raw tuple describes a text
538 * encoding, and the same for anything lacking the private
539 * attribute.
540 */
541 if (!PyTuple_CheckExact(codec)) {
542 attr = _PyObject_GetAttrId(codec, &PyId__is_text_encoding);
543 if (attr == NULL) {
544 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
545 PyErr_Clear();
546 } else {
547 Py_DECREF(codec);
548 return NULL;
549 }
550 } else {
551 is_text_codec = PyObject_IsTrue(attr);
552 Py_DECREF(attr);
553 if (!is_text_codec) {
554 Py_DECREF(codec);
555 PyErr_Format(PyExc_LookupError,
556 "'%.400s' is not a text encoding; "
Nick Coghlana9b15242014-02-04 22:11:18 +1000557 "use %s to handle arbitrary codecs",
558 encoding, alternate_command);
Nick Coghlanc72e4e62013-11-22 22:39:36 +1000559 return NULL;
560 }
561 }
562 }
563
Nick Coghlana9b15242014-02-04 22:11:18 +1000564 /* This appears to be a valid text encoding */
565 return codec;
566}
567
568
569static
570PyObject *codec_getitem_checked(const char *encoding,
571 const char *alternate_command,
572 int index)
573{
574 PyObject *codec;
575 PyObject *v;
576
577 codec = _PyCodec_LookupTextEncoding(encoding, alternate_command);
578 if (codec == NULL)
579 return NULL;
580
Nick Coghlanc72e4e62013-11-22 22:39:36 +1000581 v = PyTuple_GET_ITEM(codec, index);
Nick Coghlanc72e4e62013-11-22 22:39:36 +1000582 Py_INCREF(v);
Nick Coghlana9b15242014-02-04 22:11:18 +1000583 Py_DECREF(codec);
Nick Coghlanc72e4e62013-11-22 22:39:36 +1000584 return v;
585}
586
587static PyObject * _PyCodec_TextEncoder(const char *encoding)
588{
Nick Coghlana9b15242014-02-04 22:11:18 +1000589 return codec_getitem_checked(encoding, "codecs.encode()", 0);
Nick Coghlanc72e4e62013-11-22 22:39:36 +1000590}
591
592static PyObject * _PyCodec_TextDecoder(const char *encoding)
593{
Nick Coghlana9b15242014-02-04 22:11:18 +1000594 return codec_getitem_checked(encoding, "codecs.decode()", 1);
Nick Coghlanc72e4e62013-11-22 22:39:36 +1000595}
596
597PyObject *_PyCodec_EncodeText(PyObject *object,
598 const char *encoding,
599 const char *errors)
600{
601 PyObject *encoder;
602
603 encoder = _PyCodec_TextEncoder(encoding);
604 if (encoder == NULL)
605 return NULL;
606
607 return _PyCodec_EncodeInternal(object, encoder, encoding, errors);
608}
609
610PyObject *_PyCodec_DecodeText(PyObject *object,
611 const char *encoding,
612 const char *errors)
613{
614 PyObject *decoder;
615
616 decoder = _PyCodec_TextDecoder(encoding);
617 if (decoder == NULL)
618 return NULL;
619
620 return _PyCodec_DecodeInternal(object, decoder, encoding, errors);
621}
622
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000623/* Register the error handling callback function error under the name
624 name. This function will be called by the codec when it encounters
625 an unencodable characters/undecodable bytes and doesn't know the
626 callback name, when name is specified as the error parameter
627 in the call to the encode/decode function.
628 Return 0 on success, -1 on error */
629int PyCodec_RegisterError(const char *name, PyObject *error)
630{
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000631 PyInterpreterState *interp = PyThreadState_GET()->interp;
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000632 if (interp->codec_search_path == NULL && _PyCodecRegistry_Init())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000634 if (!PyCallable_Check(error)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 PyErr_SetString(PyExc_TypeError, "handler must be callable");
636 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000637 }
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000638 return PyDict_SetItemString(interp->codec_error_registry,
Serhiy Storchakac6792272013-10-19 21:03:34 +0300639 name, error);
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000640}
641
642/* Lookup the error handling callback function registered under the
643 name error. As a special case NULL can be passed, in which case
644 the error handling callback for strict encoding will be returned. */
645PyObject *PyCodec_LookupError(const char *name)
646{
647 PyObject *handler = NULL;
648
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000649 PyInterpreterState *interp = PyThreadState_GET()->interp;
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000650 if (interp->codec_search_path == NULL && _PyCodecRegistry_Init())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 return NULL;
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +0000652
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000653 if (name==NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 name = "strict";
Serhiy Storchakac6792272013-10-19 21:03:34 +0300655 handler = PyDict_GetItemString(interp->codec_error_registry, name);
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000656 if (!handler)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 PyErr_Format(PyExc_LookupError, "unknown error handler name '%.400s'", name);
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000658 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 Py_INCREF(handler);
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000660 return handler;
661}
662
663static void wrong_exception_type(PyObject *exc)
664{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200665 _Py_IDENTIFIER(__class__);
666 _Py_IDENTIFIER(__name__);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200667 PyObject *type = _PyObject_GetAttrId(exc, &PyId___class__);
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000668 if (type != NULL) {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200669 PyObject *name = _PyObject_GetAttrId(type, &PyId___name__);
Walter Dörwald573c08c2007-05-25 15:46:59 +0000670 Py_DECREF(type);
671 if (name != NULL) {
672 PyErr_Format(PyExc_TypeError,
673 "don't know how to handle %S in error callback", name);
674 Py_DECREF(name);
675 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000676 }
677}
678
679PyObject *PyCodec_StrictErrors(PyObject *exc)
680{
Brett Cannonbf364092006-03-01 04:25:17 +0000681 if (PyExceptionInstance_Check(exc))
682 PyErr_SetObject(PyExceptionInstance_Class(exc), exc);
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000683 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 PyErr_SetString(PyExc_TypeError, "codec must pass exception instance");
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000685 return NULL;
686}
687
688
689PyObject *PyCodec_IgnoreErrors(PyObject *exc)
690{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000691 Py_ssize_t end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000692 if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 if (PyUnicodeEncodeError_GetEnd(exc, &end))
694 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000695 }
696 else if (PyObject_IsInstance(exc, PyExc_UnicodeDecodeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 if (PyUnicodeDecodeError_GetEnd(exc, &end))
698 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000699 }
700 else if (PyObject_IsInstance(exc, PyExc_UnicodeTranslateError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 if (PyUnicodeTranslateError_GetEnd(exc, &end))
702 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000703 }
704 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 wrong_exception_type(exc);
706 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000707 }
Victor Stinneree450092011-12-01 02:52:11 +0100708 return Py_BuildValue("(Nn)", PyUnicode_New(0, 0), end);
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000709}
710
711
712PyObject *PyCodec_ReplaceErrors(PyObject *exc)
713{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200714 Py_ssize_t start, end, i, len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000715
716 if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 PyObject *res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200718 int kind;
719 void *data;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 if (PyUnicodeEncodeError_GetStart(exc, &start))
721 return NULL;
722 if (PyUnicodeEncodeError_GetEnd(exc, &end))
723 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200724 len = end - start;
725 res = PyUnicode_New(len, '?');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 if (res == NULL)
727 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200728 kind = PyUnicode_KIND(res);
729 data = PyUnicode_DATA(res);
730 for (i = 0; i < len; ++i)
731 PyUnicode_WRITE(kind, data, i, '?');
Victor Stinner8f825062012-04-27 13:55:39 +0200732 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200733 return Py_BuildValue("(Nn)", res, end);
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000734 }
735 else if (PyObject_IsInstance(exc, PyExc_UnicodeDecodeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 if (PyUnicodeDecodeError_GetEnd(exc, &end))
737 return NULL;
Victor Stinner1a15aba2011-10-02 19:00:15 +0200738 return Py_BuildValue("(Cn)",
739 (int)Py_UNICODE_REPLACEMENT_CHARACTER,
740 end);
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000741 }
742 else if (PyObject_IsInstance(exc, PyExc_UnicodeTranslateError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 PyObject *res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200744 int kind;
745 void *data;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 if (PyUnicodeTranslateError_GetStart(exc, &start))
747 return NULL;
748 if (PyUnicodeTranslateError_GetEnd(exc, &end))
749 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200750 len = end - start;
751 res = PyUnicode_New(len, Py_UNICODE_REPLACEMENT_CHARACTER);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 if (res == NULL)
753 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200754 kind = PyUnicode_KIND(res);
755 data = PyUnicode_DATA(res);
756 for (i=0; i < len; i++)
757 PyUnicode_WRITE(kind, data, i, Py_UNICODE_REPLACEMENT_CHARACTER);
Victor Stinner8f825062012-04-27 13:55:39 +0200758 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200759 return Py_BuildValue("(Nn)", res, end);
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000760 }
761 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 wrong_exception_type(exc);
763 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000764 }
765}
766
767PyObject *PyCodec_XMLCharRefReplaceErrors(PyObject *exc)
768{
769 if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 PyObject *restuple;
771 PyObject *object;
Victor Stinnerb31f1bc2011-11-04 21:29:10 +0100772 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 Py_ssize_t start;
774 Py_ssize_t end;
775 PyObject *res;
Martin v. Löwisb09af032011-11-04 11:16:41 +0100776 unsigned char *outp;
Serhiy Storchaka2e374092014-10-04 14:15:49 +0300777 Py_ssize_t ressize;
Martin v. Löwisb09af032011-11-04 11:16:41 +0100778 Py_UCS4 ch;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 if (PyUnicodeEncodeError_GetStart(exc, &start))
780 return NULL;
781 if (PyUnicodeEncodeError_GetEnd(exc, &end))
782 return NULL;
783 if (!(object = PyUnicodeEncodeError_GetObject(exc)))
784 return NULL;
Serhiy Storchaka2e374092014-10-04 14:15:49 +0300785 if (end - start > PY_SSIZE_T_MAX / (2+7+1))
786 end = start + PY_SSIZE_T_MAX / (2+7+1);
Martin v. Löwisb09af032011-11-04 11:16:41 +0100787 for (i = start, ressize = 0; i < end; ++i) {
788 /* object is guaranteed to be "ready" */
789 ch = PyUnicode_READ_CHAR(object, i);
790 if (ch<10)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 ressize += 2+1+1;
Martin v. Löwisb09af032011-11-04 11:16:41 +0100792 else if (ch<100)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 ressize += 2+2+1;
Martin v. Löwisb09af032011-11-04 11:16:41 +0100794 else if (ch<1000)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 ressize += 2+3+1;
Martin v. Löwisb09af032011-11-04 11:16:41 +0100796 else if (ch<10000)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 ressize += 2+4+1;
Martin v. Löwisb09af032011-11-04 11:16:41 +0100798 else if (ch<100000)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 ressize += 2+5+1;
Martin v. Löwisb09af032011-11-04 11:16:41 +0100800 else if (ch<1000000)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 ressize += 2+6+1;
802 else
803 ressize += 2+7+1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 }
805 /* allocate replacement */
Martin v. Löwisb09af032011-11-04 11:16:41 +0100806 res = PyUnicode_New(ressize, 127);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 if (res == NULL) {
808 Py_DECREF(object);
809 return NULL;
810 }
Martin v. Löwisb09af032011-11-04 11:16:41 +0100811 outp = PyUnicode_1BYTE_DATA(res);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 /* generate replacement */
Victor Stinnerb31f1bc2011-11-04 21:29:10 +0100813 for (i = start; i < end; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 int digits;
815 int base;
Martin v. Löwis8ba79302011-11-04 12:26:49 +0100816 ch = PyUnicode_READ_CHAR(object, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 *outp++ = '&';
818 *outp++ = '#';
Martin v. Löwisb09af032011-11-04 11:16:41 +0100819 if (ch<10) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 digits = 1;
821 base = 1;
822 }
Martin v. Löwisb09af032011-11-04 11:16:41 +0100823 else if (ch<100) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 digits = 2;
825 base = 10;
826 }
Martin v. Löwisb09af032011-11-04 11:16:41 +0100827 else if (ch<1000) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 digits = 3;
829 base = 100;
830 }
Martin v. Löwisb09af032011-11-04 11:16:41 +0100831 else if (ch<10000) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 digits = 4;
833 base = 1000;
834 }
Martin v. Löwisb09af032011-11-04 11:16:41 +0100835 else if (ch<100000) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 digits = 5;
837 base = 10000;
838 }
Martin v. Löwisb09af032011-11-04 11:16:41 +0100839 else if (ch<1000000) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 digits = 6;
841 base = 100000;
842 }
843 else {
844 digits = 7;
845 base = 1000000;
846 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 while (digits-->0) {
Martin v. Löwisb09af032011-11-04 11:16:41 +0100848 *outp++ = '0' + ch/base;
849 ch %= base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 base /= 10;
851 }
852 *outp++ = ';';
853 }
Victor Stinner8f825062012-04-27 13:55:39 +0200854 assert(_PyUnicode_CheckConsistency(res, 1));
855 restuple = Py_BuildValue("(Nn)", res, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 Py_DECREF(object);
857 return restuple;
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000858 }
859 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 wrong_exception_type(exc);
861 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000862 }
863}
864
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000865PyObject *PyCodec_BackslashReplaceErrors(PyObject *exc)
866{
867 if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 PyObject *restuple;
869 PyObject *object;
Martin v. Löwisb09af032011-11-04 11:16:41 +0100870 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 Py_ssize_t start;
872 Py_ssize_t end;
873 PyObject *res;
Martin v. Löwisb09af032011-11-04 11:16:41 +0100874 unsigned char *outp;
Serhiy Storchaka2e374092014-10-04 14:15:49 +0300875 Py_ssize_t ressize;
Martin v. Löwisb09af032011-11-04 11:16:41 +0100876 Py_UCS4 c;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 if (PyUnicodeEncodeError_GetStart(exc, &start))
878 return NULL;
879 if (PyUnicodeEncodeError_GetEnd(exc, &end))
880 return NULL;
881 if (!(object = PyUnicodeEncodeError_GetObject(exc)))
882 return NULL;
Serhiy Storchaka2e374092014-10-04 14:15:49 +0300883 if (end - start > PY_SSIZE_T_MAX / (1+1+8))
884 end = start + PY_SSIZE_T_MAX / (1+1+8);
Martin v. Löwisb09af032011-11-04 11:16:41 +0100885 for (i = start, ressize = 0; i < end; ++i) {
886 /* object is guaranteed to be "ready" */
887 c = PyUnicode_READ_CHAR(object, i);
888 if (c >= 0x10000) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 ressize += 1+1+8;
Martin v. Löwisb09af032011-11-04 11:16:41 +0100890 }
891 else if (c >= 0x100) {
892 ressize += 1+1+4;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 }
894 else
895 ressize += 1+1+2;
896 }
Martin v. Löwisb09af032011-11-04 11:16:41 +0100897 res = PyUnicode_New(ressize, 127);
Serhiy Storchaka8aa8c472014-09-23 19:59:09 +0300898 if (res == NULL) {
899 Py_DECREF(object);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 return NULL;
Serhiy Storchaka8aa8c472014-09-23 19:59:09 +0300901 }
Martin v. Löwisb09af032011-11-04 11:16:41 +0100902 for (i = start, outp = PyUnicode_1BYTE_DATA(res);
903 i < end; ++i) {
904 c = PyUnicode_READ_CHAR(object, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 *outp++ = '\\';
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 if (c >= 0x00010000) {
907 *outp++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +0200908 *outp++ = Py_hexdigits[(c>>28)&0xf];
909 *outp++ = Py_hexdigits[(c>>24)&0xf];
910 *outp++ = Py_hexdigits[(c>>20)&0xf];
911 *outp++ = Py_hexdigits[(c>>16)&0xf];
912 *outp++ = Py_hexdigits[(c>>12)&0xf];
913 *outp++ = Py_hexdigits[(c>>8)&0xf];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 }
Antoine Pitroue4a18922010-09-09 20:30:23 +0000915 else if (c >= 0x100) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 *outp++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +0200917 *outp++ = Py_hexdigits[(c>>12)&0xf];
918 *outp++ = Py_hexdigits[(c>>8)&0xf];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 }
920 else
921 *outp++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +0200922 *outp++ = Py_hexdigits[(c>>4)&0xf];
923 *outp++ = Py_hexdigits[c&0xf];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000925
Victor Stinner8f825062012-04-27 13:55:39 +0200926 assert(_PyUnicode_CheckConsistency(res, 1));
927 restuple = Py_BuildValue("(Nn)", res, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 Py_DECREF(object);
929 return restuple;
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000930 }
931 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 wrong_exception_type(exc);
933 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000934 }
935}
936
Serhiy Storchaka166ebc42014-11-25 13:57:17 +0200937static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
938static int ucnhash_initialized = 0;
939
940PyObject *PyCodec_NameReplaceErrors(PyObject *exc)
941{
942 if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) {
943 PyObject *restuple;
944 PyObject *object;
945 Py_ssize_t i;
946 Py_ssize_t start;
947 Py_ssize_t end;
948 PyObject *res;
949 unsigned char *outp;
Serhiy Storchakaaacfccc2014-11-26 12:11:40 +0200950 Py_ssize_t ressize;
951 int replsize;
Serhiy Storchaka166ebc42014-11-25 13:57:17 +0200952 Py_UCS4 c;
953 char buffer[256]; /* NAME_MAXLEN */
954 if (PyUnicodeEncodeError_GetStart(exc, &start))
955 return NULL;
956 if (PyUnicodeEncodeError_GetEnd(exc, &end))
957 return NULL;
958 if (!(object = PyUnicodeEncodeError_GetObject(exc)))
959 return NULL;
960 if (!ucnhash_initialized) {
961 /* load the unicode data module */
962 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
963 PyUnicodeData_CAPSULE_NAME, 1);
964 ucnhash_initialized = 1;
965 }
966 for (i = start, ressize = 0; i < end; ++i) {
967 /* object is guaranteed to be "ready" */
968 c = PyUnicode_READ_CHAR(object, i);
969 if (ucnhash_CAPI &&
970 ucnhash_CAPI->getname(NULL, c, buffer, sizeof(buffer), 1)) {
Serhiy Storchakaaacfccc2014-11-26 12:11:40 +0200971 replsize = 1+1+1+strlen(buffer)+1;
Serhiy Storchaka166ebc42014-11-25 13:57:17 +0200972 }
973 else if (c >= 0x10000) {
Serhiy Storchakaaacfccc2014-11-26 12:11:40 +0200974 replsize = 1+1+8;
Serhiy Storchaka166ebc42014-11-25 13:57:17 +0200975 }
976 else if (c >= 0x100) {
Serhiy Storchakaaacfccc2014-11-26 12:11:40 +0200977 replsize = 1+1+4;
Serhiy Storchaka166ebc42014-11-25 13:57:17 +0200978 }
979 else
Serhiy Storchakaaacfccc2014-11-26 12:11:40 +0200980 replsize = 1+1+2;
981 if (ressize > PY_SSIZE_T_MAX - replsize)
982 break;
983 ressize += replsize;
Serhiy Storchaka166ebc42014-11-25 13:57:17 +0200984 }
Serhiy Storchakaaacfccc2014-11-26 12:11:40 +0200985 end = i;
Serhiy Storchaka166ebc42014-11-25 13:57:17 +0200986 res = PyUnicode_New(ressize, 127);
987 if (res==NULL)
988 return NULL;
989 for (i = start, outp = PyUnicode_1BYTE_DATA(res);
990 i < end; ++i) {
991 c = PyUnicode_READ_CHAR(object, i);
992 *outp++ = '\\';
993 if (ucnhash_CAPI &&
994 ucnhash_CAPI->getname(NULL, c, buffer, sizeof(buffer), 1)) {
995 *outp++ = 'N';
996 *outp++ = '{';
997 strcpy((char *)outp, buffer);
998 outp += strlen(buffer);
999 *outp++ = '}';
1000 continue;
1001 }
1002 if (c >= 0x00010000) {
1003 *outp++ = 'U';
1004 *outp++ = Py_hexdigits[(c>>28)&0xf];
1005 *outp++ = Py_hexdigits[(c>>24)&0xf];
1006 *outp++ = Py_hexdigits[(c>>20)&0xf];
1007 *outp++ = Py_hexdigits[(c>>16)&0xf];
1008 *outp++ = Py_hexdigits[(c>>12)&0xf];
1009 *outp++ = Py_hexdigits[(c>>8)&0xf];
1010 }
1011 else if (c >= 0x100) {
1012 *outp++ = 'u';
1013 *outp++ = Py_hexdigits[(c>>12)&0xf];
1014 *outp++ = Py_hexdigits[(c>>8)&0xf];
1015 }
1016 else
1017 *outp++ = 'x';
1018 *outp++ = Py_hexdigits[(c>>4)&0xf];
1019 *outp++ = Py_hexdigits[c&0xf];
1020 }
1021
Benjamin Peterson3663b582014-11-26 14:39:54 -06001022 assert(outp == PyUnicode_1BYTE_DATA(res) + ressize);
Serhiy Storchaka166ebc42014-11-25 13:57:17 +02001023 assert(_PyUnicode_CheckConsistency(res, 1));
1024 restuple = Py_BuildValue("(Nn)", res, end);
1025 Py_DECREF(object);
1026 return restuple;
1027 }
1028 else {
1029 wrong_exception_type(exc);
1030 return NULL;
1031 }
1032}
1033
Serhiy Storchaka88d8fb62014-05-15 14:37:42 +03001034#define ENC_UNKNOWN -1
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001035#define ENC_UTF8 0
1036#define ENC_UTF16BE 1
1037#define ENC_UTF16LE 2
1038#define ENC_UTF32BE 3
1039#define ENC_UTF32LE 4
1040
1041static int
1042get_standard_encoding(const char *encoding, int *bytelength)
1043{
1044 if (Py_TOLOWER(encoding[0]) == 'u' &&
1045 Py_TOLOWER(encoding[1]) == 't' &&
1046 Py_TOLOWER(encoding[2]) == 'f') {
1047 encoding += 3;
1048 if (*encoding == '-' || *encoding == '_' )
1049 encoding++;
Serhiy Storchaka88d8fb62014-05-15 14:37:42 +03001050 if (encoding[0] == '8' && encoding[1] == '\0') {
1051 *bytelength = 3;
1052 return ENC_UTF8;
1053 }
1054 else if (encoding[0] == '1' && encoding[1] == '6') {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001055 encoding += 2;
1056 *bytelength = 2;
1057 if (*encoding == '\0') {
1058#ifdef WORDS_BIGENDIAN
1059 return ENC_UTF16BE;
1060#else
1061 return ENC_UTF16LE;
1062#endif
1063 }
1064 if (*encoding == '-' || *encoding == '_' )
1065 encoding++;
1066 if (Py_TOLOWER(encoding[1]) == 'e' && encoding[2] == '\0') {
1067 if (Py_TOLOWER(encoding[0]) == 'b')
1068 return ENC_UTF16BE;
1069 if (Py_TOLOWER(encoding[0]) == 'l')
1070 return ENC_UTF16LE;
1071 }
1072 }
1073 else if (encoding[0] == '3' && encoding[1] == '2') {
1074 encoding += 2;
1075 *bytelength = 4;
1076 if (*encoding == '\0') {
1077#ifdef WORDS_BIGENDIAN
1078 return ENC_UTF32BE;
1079#else
1080 return ENC_UTF32LE;
1081#endif
1082 }
1083 if (*encoding == '-' || *encoding == '_' )
1084 encoding++;
1085 if (Py_TOLOWER(encoding[1]) == 'e' && encoding[2] == '\0') {
1086 if (Py_TOLOWER(encoding[0]) == 'b')
1087 return ENC_UTF32BE;
1088 if (Py_TOLOWER(encoding[0]) == 'l')
1089 return ENC_UTF32LE;
1090 }
1091 }
1092 }
Victor Stinner0d4e01c2014-05-16 14:46:20 +02001093 else if (strcmp(encoding, "CP_UTF8") == 0) {
1094 *bytelength = 3;
1095 return ENC_UTF8;
1096 }
Serhiy Storchaka88d8fb62014-05-15 14:37:42 +03001097 return ENC_UNKNOWN;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001098}
1099
Martin v. Löwisaef3fb02009-05-02 19:27:30 +00001100/* This handler is declared static until someone demonstrates
1101 a need to call it directly. */
1102static PyObject *
Martin v. Löwise0a2b722009-05-10 08:08:56 +00001103PyCodec_SurrogatePassErrors(PyObject *exc)
Martin v. Löwisdb12d452009-05-02 18:52:14 +00001104{
1105 PyObject *restuple;
1106 PyObject *object;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001107 PyObject *encode;
1108 char *encoding;
1109 int code;
1110 int bytelength;
Martin v. Löwisb09af032011-11-04 11:16:41 +01001111 Py_ssize_t i;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00001112 Py_ssize_t start;
1113 Py_ssize_t end;
1114 PyObject *res;
1115 if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001116 unsigned char *outp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 if (PyUnicodeEncodeError_GetStart(exc, &start))
1118 return NULL;
1119 if (PyUnicodeEncodeError_GetEnd(exc, &end))
1120 return NULL;
1121 if (!(object = PyUnicodeEncodeError_GetObject(exc)))
1122 return NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001123 if (!(encode = PyUnicodeEncodeError_GetEncoding(exc))) {
1124 Py_DECREF(object);
1125 return NULL;
1126 }
1127 if (!(encoding = PyUnicode_AsUTF8(encode))) {
1128 Py_DECREF(object);
1129 Py_DECREF(encode);
1130 return NULL;
1131 }
1132 code = get_standard_encoding(encoding, &bytelength);
1133 Py_DECREF(encode);
Serhiy Storchaka88d8fb62014-05-15 14:37:42 +03001134 if (code == ENC_UNKNOWN) {
1135 /* Not supported, fail with original exception */
1136 PyErr_SetObject(PyExceptionInstance_Class(exc), exc);
1137 Py_DECREF(object);
1138 return NULL;
1139 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001140
Serhiy Storchaka2e374092014-10-04 14:15:49 +03001141 if (end - start > PY_SSIZE_T_MAX / bytelength)
1142 end = start + PY_SSIZE_T_MAX / bytelength;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001143 res = PyBytes_FromStringAndSize(NULL, bytelength*(end-start));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 if (!res) {
1145 Py_DECREF(object);
1146 return NULL;
1147 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001148 outp = (unsigned char*)PyBytes_AsString(res);
Martin v. Löwisb09af032011-11-04 11:16:41 +01001149 for (i = start; i < end; i++) {
1150 /* object is guaranteed to be "ready" */
1151 Py_UCS4 ch = PyUnicode_READ_CHAR(object, i);
Victor Stinner76df43d2012-10-30 01:42:39 +01001152 if (!Py_UNICODE_IS_SURROGATE(ch)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 /* Not a surrogate, fail with original exception */
1154 PyErr_SetObject(PyExceptionInstance_Class(exc), exc);
1155 Py_DECREF(res);
1156 Py_DECREF(object);
1157 return NULL;
1158 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001159 switch (code) {
1160 case ENC_UTF8:
1161 *outp++ = (unsigned char)(0xe0 | (ch >> 12));
1162 *outp++ = (unsigned char)(0x80 | ((ch >> 6) & 0x3f));
1163 *outp++ = (unsigned char)(0x80 | (ch & 0x3f));
1164 break;
1165 case ENC_UTF16LE:
1166 *outp++ = (unsigned char) ch;
1167 *outp++ = (unsigned char)(ch >> 8);
1168 break;
1169 case ENC_UTF16BE:
1170 *outp++ = (unsigned char)(ch >> 8);
1171 *outp++ = (unsigned char) ch;
1172 break;
1173 case ENC_UTF32LE:
1174 *outp++ = (unsigned char) ch;
1175 *outp++ = (unsigned char)(ch >> 8);
1176 *outp++ = (unsigned char)(ch >> 16);
1177 *outp++ = (unsigned char)(ch >> 24);
1178 break;
1179 case ENC_UTF32BE:
1180 *outp++ = (unsigned char)(ch >> 24);
1181 *outp++ = (unsigned char)(ch >> 16);
1182 *outp++ = (unsigned char)(ch >> 8);
1183 *outp++ = (unsigned char) ch;
1184 break;
1185 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 }
1187 restuple = Py_BuildValue("(On)", res, end);
1188 Py_DECREF(res);
1189 Py_DECREF(object);
1190 return restuple;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00001191 }
1192 else if (PyObject_IsInstance(exc, PyExc_UnicodeDecodeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 unsigned char *p;
Victor Stinnerc06bb7a2011-11-04 21:36:35 +01001194 Py_UCS4 ch = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 if (PyUnicodeDecodeError_GetStart(exc, &start))
1196 return NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001197 if (PyUnicodeDecodeError_GetEnd(exc, &end))
1198 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 if (!(object = PyUnicodeDecodeError_GetObject(exc)))
1200 return NULL;
1201 if (!(p = (unsigned char*)PyBytes_AsString(object))) {
1202 Py_DECREF(object);
1203 return NULL;
1204 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001205 if (!(encode = PyUnicodeDecodeError_GetEncoding(exc))) {
1206 Py_DECREF(object);
1207 return NULL;
1208 }
1209 if (!(encoding = PyUnicode_AsUTF8(encode))) {
1210 Py_DECREF(object);
1211 Py_DECREF(encode);
1212 return NULL;
1213 }
1214 code = get_standard_encoding(encoding, &bytelength);
1215 Py_DECREF(encode);
Serhiy Storchaka88d8fb62014-05-15 14:37:42 +03001216 if (code == ENC_UNKNOWN) {
1217 /* Not supported, fail with original exception */
1218 PyErr_SetObject(PyExceptionInstance_Class(exc), exc);
1219 Py_DECREF(object);
1220 return NULL;
1221 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 /* Try decoding a single surrogate character. If
1224 there are more, let the codec call us again. */
1225 p += start;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001226 if (PyBytes_GET_SIZE(object) - start >= bytelength) {
1227 switch (code) {
1228 case ENC_UTF8:
1229 if ((p[0] & 0xf0) == 0xe0 &&
1230 (p[1] & 0xc0) == 0x80 &&
1231 (p[2] & 0xc0) == 0x80) {
1232 /* it's a three-byte code */
1233 ch = ((p[0] & 0x0f) << 12) + ((p[1] & 0x3f) << 6) + (p[2] & 0x3f);
1234 }
1235 break;
1236 case ENC_UTF16LE:
1237 ch = p[1] << 8 | p[0];
1238 break;
1239 case ENC_UTF16BE:
1240 ch = p[0] << 8 | p[1];
1241 break;
1242 case ENC_UTF32LE:
1243 ch = (p[3] << 24) | (p[2] << 16) | (p[1] << 8) | p[0];
1244 break;
1245 case ENC_UTF32BE:
1246 ch = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
1247 break;
1248 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 Py_DECREF(object);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001252 if (!Py_UNICODE_IS_SURROGATE(ch)) {
1253 /* it's not a surrogate - fail */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 PyErr_SetObject(PyExceptionInstance_Class(exc), exc);
1255 return NULL;
1256 }
Victor Stinnerc06bb7a2011-11-04 21:36:35 +01001257 res = PyUnicode_FromOrdinal(ch);
1258 if (res == NULL)
1259 return NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001260 return Py_BuildValue("(Nn)", res, start + bytelength);
Martin v. Löwisdb12d452009-05-02 18:52:14 +00001261 }
1262 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 wrong_exception_type(exc);
1264 return NULL;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00001265 }
1266}
1267
Martin v. Löwis011e8422009-05-05 04:43:17 +00001268static PyObject *
Martin v. Löwis43c57782009-05-10 08:15:24 +00001269PyCodec_SurrogateEscapeErrors(PyObject *exc)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001270{
1271 PyObject *restuple;
1272 PyObject *object;
Martin v. Löwisb09af032011-11-04 11:16:41 +01001273 Py_ssize_t i;
Martin v. Löwis011e8422009-05-05 04:43:17 +00001274 Py_ssize_t start;
1275 Py_ssize_t end;
1276 PyObject *res;
1277 if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 char *outp;
1279 if (PyUnicodeEncodeError_GetStart(exc, &start))
1280 return NULL;
1281 if (PyUnicodeEncodeError_GetEnd(exc, &end))
1282 return NULL;
1283 if (!(object = PyUnicodeEncodeError_GetObject(exc)))
1284 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 res = PyBytes_FromStringAndSize(NULL, end-start);
1286 if (!res) {
1287 Py_DECREF(object);
1288 return NULL;
1289 }
1290 outp = PyBytes_AsString(res);
Martin v. Löwisb09af032011-11-04 11:16:41 +01001291 for (i = start; i < end; i++) {
1292 /* object is guaranteed to be "ready" */
1293 Py_UCS4 ch = PyUnicode_READ_CHAR(object, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 if (ch < 0xdc80 || ch > 0xdcff) {
1295 /* Not a UTF-8b surrogate, fail with original exception */
1296 PyErr_SetObject(PyExceptionInstance_Class(exc), exc);
1297 Py_DECREF(res);
1298 Py_DECREF(object);
1299 return NULL;
1300 }
1301 *outp++ = ch - 0xdc00;
1302 }
1303 restuple = Py_BuildValue("(On)", res, end);
1304 Py_DECREF(res);
1305 Py_DECREF(object);
1306 return restuple;
Martin v. Löwis011e8422009-05-05 04:43:17 +00001307 }
1308 else if (PyObject_IsInstance(exc, PyExc_UnicodeDecodeError)) {
Victor Stinnerc06bb7a2011-11-04 21:36:35 +01001309 PyObject *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 unsigned char *p;
Victor Stinnerc06bb7a2011-11-04 21:36:35 +01001311 Py_UCS2 ch[4]; /* decode up to 4 bad bytes. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 int consumed = 0;
1313 if (PyUnicodeDecodeError_GetStart(exc, &start))
1314 return NULL;
1315 if (PyUnicodeDecodeError_GetEnd(exc, &end))
1316 return NULL;
1317 if (!(object = PyUnicodeDecodeError_GetObject(exc)))
1318 return NULL;
1319 if (!(p = (unsigned char*)PyBytes_AsString(object))) {
1320 Py_DECREF(object);
1321 return NULL;
1322 }
1323 while (consumed < 4 && consumed < end-start) {
1324 /* Refuse to escape ASCII bytes. */
1325 if (p[start+consumed] < 128)
1326 break;
1327 ch[consumed] = 0xdc00 + p[start+consumed];
1328 consumed++;
1329 }
1330 Py_DECREF(object);
1331 if (!consumed) {
1332 /* codec complained about ASCII byte. */
1333 PyErr_SetObject(PyExceptionInstance_Class(exc), exc);
1334 return NULL;
1335 }
Victor Stinnerc06bb7a2011-11-04 21:36:35 +01001336 str = PyUnicode_FromKindAndData(PyUnicode_2BYTE_KIND, ch, consumed);
1337 if (str == NULL)
1338 return NULL;
1339 return Py_BuildValue("(Nn)", str, start+consumed);
Martin v. Löwis011e8422009-05-05 04:43:17 +00001340 }
1341 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 wrong_exception_type(exc);
1343 return NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00001344 }
1345}
1346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001348static PyObject *strict_errors(PyObject *self, PyObject *exc)
1349{
1350 return PyCodec_StrictErrors(exc);
1351}
1352
1353
1354static PyObject *ignore_errors(PyObject *self, PyObject *exc)
1355{
1356 return PyCodec_IgnoreErrors(exc);
1357}
1358
1359
1360static PyObject *replace_errors(PyObject *self, PyObject *exc)
1361{
1362 return PyCodec_ReplaceErrors(exc);
1363}
1364
1365
1366static PyObject *xmlcharrefreplace_errors(PyObject *self, PyObject *exc)
1367{
1368 return PyCodec_XMLCharRefReplaceErrors(exc);
1369}
1370
1371
1372static PyObject *backslashreplace_errors(PyObject *self, PyObject *exc)
1373{
1374 return PyCodec_BackslashReplaceErrors(exc);
1375}
1376
Serhiy Storchaka166ebc42014-11-25 13:57:17 +02001377static PyObject *namereplace_errors(PyObject *self, PyObject *exc)
1378{
1379 return PyCodec_NameReplaceErrors(exc);
1380}
1381
Martin v. Löwise0a2b722009-05-10 08:08:56 +00001382static PyObject *surrogatepass_errors(PyObject *self, PyObject *exc)
Martin v. Löwisdb12d452009-05-02 18:52:14 +00001383{
Martin v. Löwise0a2b722009-05-10 08:08:56 +00001384 return PyCodec_SurrogatePassErrors(exc);
Martin v. Löwisdb12d452009-05-02 18:52:14 +00001385}
1386
Martin v. Löwis43c57782009-05-10 08:15:24 +00001387static PyObject *surrogateescape_errors(PyObject *self, PyObject *exc)
Martin v. Löwis011e8422009-05-05 04:43:17 +00001388{
Martin v. Löwis43c57782009-05-10 08:15:24 +00001389 return PyCodec_SurrogateEscapeErrors(exc);
Martin v. Löwis011e8422009-05-05 04:43:17 +00001390}
1391
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +00001392static int _PyCodecRegistry_Init(void)
Guido van Rossumfeee4b92000-03-10 22:57:27 +00001393{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001394 static struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 char *name;
1396 PyMethodDef def;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001397 } methods[] =
1398 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 {
1400 "strict",
1401 {
1402 "strict_errors",
1403 strict_errors,
1404 METH_O,
1405 PyDoc_STR("Implements the 'strict' error handling, which "
1406 "raises a UnicodeError on coding errors.")
1407 }
1408 },
1409 {
1410 "ignore",
1411 {
1412 "ignore_errors",
1413 ignore_errors,
1414 METH_O,
1415 PyDoc_STR("Implements the 'ignore' error handling, which "
1416 "ignores malformed data and continues.")
1417 }
1418 },
1419 {
1420 "replace",
1421 {
1422 "replace_errors",
1423 replace_errors,
1424 METH_O,
1425 PyDoc_STR("Implements the 'replace' error handling, which "
1426 "replaces malformed data with a replacement marker.")
1427 }
1428 },
1429 {
1430 "xmlcharrefreplace",
1431 {
1432 "xmlcharrefreplace_errors",
1433 xmlcharrefreplace_errors,
1434 METH_O,
1435 PyDoc_STR("Implements the 'xmlcharrefreplace' error handling, "
1436 "which replaces an unencodable character with the "
1437 "appropriate XML character reference.")
1438 }
1439 },
1440 {
1441 "backslashreplace",
1442 {
1443 "backslashreplace_errors",
1444 backslashreplace_errors,
1445 METH_O,
1446 PyDoc_STR("Implements the 'backslashreplace' error handling, "
1447 "which replaces an unencodable character with a "
1448 "backslashed escape sequence.")
1449 }
1450 },
1451 {
Serhiy Storchaka166ebc42014-11-25 13:57:17 +02001452 "namereplace",
1453 {
1454 "namereplace_errors",
1455 namereplace_errors,
1456 METH_O,
1457 PyDoc_STR("Implements the 'namereplace' error handling, "
1458 "which replaces an unencodable character with a "
1459 "\\N{...} escape sequence.")
1460 }
1461 },
1462 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 "surrogatepass",
1464 {
1465 "surrogatepass",
1466 surrogatepass_errors,
1467 METH_O
1468 }
1469 },
1470 {
1471 "surrogateescape",
1472 {
1473 "surrogateescape",
1474 surrogateescape_errors,
1475 METH_O
1476 }
1477 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001478 };
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001479
Nicholas Bastine5662ae2004-03-24 22:22:12 +00001480 PyInterpreterState *interp = PyThreadState_GET()->interp;
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +00001481 PyObject *mod;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001482 unsigned i;
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +00001483
1484 if (interp->codec_search_path != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 return 0;
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +00001486
1487 interp->codec_search_path = PyList_New(0);
1488 interp->codec_search_cache = PyDict_New();
1489 interp->codec_error_registry = PyDict_New();
1490
1491 if (interp->codec_error_registry) {
Victor Stinner63941882011-09-29 00:42:28 +02001492 for (i = 0; i < Py_ARRAY_LENGTH(methods); ++i) {
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +02001493 PyObject *func = PyCFunction_NewEx(&methods[i].def, NULL, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 int res;
1495 if (!func)
1496 Py_FatalError("can't initialize codec error registry");
1497 res = PyCodec_RegisterError(methods[i].name, func);
1498 Py_DECREF(func);
1499 if (res)
1500 Py_FatalError("can't initialize codec error registry");
1501 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001502 }
Guido van Rossumfeee4b92000-03-10 22:57:27 +00001503
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +00001504 if (interp->codec_search_path == NULL ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 interp->codec_search_cache == NULL ||
1506 interp->codec_error_registry == NULL)
1507 Py_FatalError("can't initialize codec registry");
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +00001508
Christian Heimes819b8bf2008-01-03 23:05:47 +00001509 mod = PyImport_ImportModuleNoBlock("encodings");
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +00001510 if (mod == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 return -1;
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +00001512 }
1513 Py_DECREF(mod);
Christian Heimes6a27efa2008-10-30 21:48:26 +00001514 interp->codecs_initialized = 1;
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +00001515 return 0;
Guido van Rossumfeee4b92000-03-10 22:57:27 +00001516}