cpython/Objects/exceptions.c
Thomas Wouters 00ee7baf49 Merge current trunk into p3yk. This includes the PyNumber_Index API change,
which unfortunately means the errors from the bytes type change somewhat:

bytes([300]) still raises a ValueError, but bytes([10**100]) now raises a
TypeError (either that, or bytes(1.0) also raises a ValueError --
PyNumber_AsSsize_t() can only raise one type of exception.)

Merged revisions 51188-51433 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk

........
  r51189 | kurt.kaiser | 2006-08-10 19:11:09 +0200 (Thu, 10 Aug 2006) | 4 lines

  Retrieval of previous shell command was not always preserving indentation
  since 1.2a1) Patch 1528468 Tal Einat.
........
  r51190 | guido.van.rossum | 2006-08-10 19:41:07 +0200 (Thu, 10 Aug 2006) | 3 lines

  Chris McDonough's patch to defend against certain DoS attacks on FieldStorage.
  SF bug #1112549.
........
  r51191 | guido.van.rossum | 2006-08-10 19:42:50 +0200 (Thu, 10 Aug 2006) | 2 lines

  News item for SF bug 1112549.
........
  r51192 | guido.van.rossum | 2006-08-10 20:09:25 +0200 (Thu, 10 Aug 2006) | 2 lines

  Fix title -- it's rc1, not beta3.
........
  r51194 | martin.v.loewis | 2006-08-10 21:04:00 +0200 (Thu, 10 Aug 2006) | 3 lines

  Update dangling references to the 3.2 database to
  mention that this is UCD 4.1 now.
........
  r51195 | tim.peters | 2006-08-11 00:45:34 +0200 (Fri, 11 Aug 2006) | 6 lines

  Followup to bug #1069160.

  PyThreadState_SetAsyncExc():  internal correctness changes wrt
  refcount safety and deadlock avoidance.  Also added a basic test
  case (relying on ctypes) and repaired the docs.
........
  r51196 | tim.peters | 2006-08-11 00:48:45 +0200 (Fri, 11 Aug 2006) | 2 lines

  Whitespace normalization.
........
  r51197 | tim.peters | 2006-08-11 01:22:13 +0200 (Fri, 11 Aug 2006) | 5 lines

  Whitespace normalization broke test_cgi, because a line
  of quoted test data relied on preserving a single trailing
  blank.  Changed the string from raw to regular, and forced
  in the trailing blank via an explicit \x20 escape.
........
  r51198 | tim.peters | 2006-08-11 02:49:01 +0200 (Fri, 11 Aug 2006) | 10 lines

  test_PyThreadState_SetAsyncExc():  This is failing on some
  64-bit boxes.  I have no idea what the ctypes docs mean
  by "integers", and blind-guessing here that it intended to
  mean the signed C "int" type, in which case perhaps I can
  repair this by feeding the thread id argument to type
  ctypes.c_long().

  Also made the worker thread daemonic, so it doesn't hang
  Python shutdown if the test continues to fail.
........
  r51199 | tim.peters | 2006-08-11 05:49:10 +0200 (Fri, 11 Aug 2006) | 6 lines

  force_test_exit():  This has been completely ineffective
  at stopping test_signal from hanging forever on the Tru64
  buildbot.  That could be because there's no such thing as
  signal.SIGALARM.  Changed to the idiotic (but standard)
  signal.SIGALRM instead, and added some more debug output.
........
  r51202 | neal.norwitz | 2006-08-11 08:09:41 +0200 (Fri, 11 Aug 2006) | 6 lines

  Fix the failures on cygwin (2006-08-10 fixed the actual locking issue).

  The first hunk changes the colon to an ! like other Windows variants.
  We need to always wait on the child so the lock gets released and
  no other tests fail.  This is the try/finally in the second hunk.
........
  r51205 | georg.brandl | 2006-08-11 09:15:38 +0200 (Fri, 11 Aug 2006) | 3 lines

  Add Chris McDonough (latest cgi.py patch)
........
  r51206 | georg.brandl | 2006-08-11 09:26:10 +0200 (Fri, 11 Aug 2006) | 3 lines

  logging's atexit hook now runs even if the rest of the module has
  already been cleaned up.
........
  r51212 | thomas.wouters | 2006-08-11 17:02:39 +0200 (Fri, 11 Aug 2006) | 4 lines


  Add ignore of *.pyc and *.pyo to Lib/xml/etree/.
........
  r51215 | thomas.heller | 2006-08-11 21:55:35 +0200 (Fri, 11 Aug 2006) | 7 lines

  When a ctypes C callback function is called, zero out the result
  storage before converting the result to C data.  See the comment in
  the code for details.

  Provide a better context for errors when the conversion of a callback
  function's result cannot be converted.
........
  r51218 | neal.norwitz | 2006-08-12 03:43:40 +0200 (Sat, 12 Aug 2006) | 6 lines

  Klocwork made another run and found a bunch more problems.
  This is the first batch of fixes that should be easy to verify based on context.

  This fixes problem numbers: 220 (ast), 323-324 (symtable),
  321-322 (structseq), 215 (array), 210 (hotshot), 182 (codecs), 209 (etree).
........
  r51219 | neal.norwitz | 2006-08-12 03:45:47 +0200 (Sat, 12 Aug 2006) | 9 lines

  Even though _Py_Mangle() isn't truly public anyone can call it and
  there was no verification that privateobj was a PyString.  If it wasn't
  a string, this could have allowed a NULL pointer to creep in below and crash.

  I wonder if this should be PyString_CheckExact?  Must identifiers be strings
  or can they be subclasses?

  Klocwork #275
........
  r51220 | neal.norwitz | 2006-08-12 03:46:42 +0200 (Sat, 12 Aug 2006) | 5 lines

  It's highly unlikely, though possible for PyEval_Get*() to return NULLs.
  So be safe and do an XINCREF.

  Klocwork # 221-222.
........
  r51221 | neal.norwitz | 2006-08-12 03:47:59 +0200 (Sat, 12 Aug 2006) | 7 lines

  This code is actually not used unless WITHOUT_COMPLEX is defined.
  However, there was no error checking that PyFloat_FromDouble returned
  a valid pointer.  I believe this change is correct as it seemed
  to follow other code in the area.

  Klocwork # 292.
........
  r51222 | neal.norwitz | 2006-08-12 03:49:12 +0200 (Sat, 12 Aug 2006) | 5 lines

  Handle NULL nodes while parsing.  I'm not entirely sure this is correct.
  There might be something else that needs to be done to setup the error.

  Klocwork #295.
........
  r51223 | neal.norwitz | 2006-08-12 03:50:38 +0200 (Sat, 12 Aug 2006) | 6 lines

  If _stat_float_times is false, we will try to INCREF ival which could be NULL.
  Return early in that case.  The caller checks for PyErr_Occurred so this
  should be ok.

  Klocwork #297
........
  r51224 | neal.norwitz | 2006-08-12 03:51:12 +0200 (Sat, 12 Aug 2006) | 3 lines

  Move the assert which checks for a NULL pointer first.
  Klocwork #274.
........
  r51225 | neal.norwitz | 2006-08-12 03:53:28 +0200 (Sat, 12 Aug 2006) | 5 lines

  Try to handle a malloc failure.  I'm not entirely sure this is correct.
  There might be something else we need to do to handle the exception.

  Klocwork # 212-213
........
  r51226 | neal.norwitz | 2006-08-12 03:57:47 +0200 (Sat, 12 Aug 2006) | 6 lines

  I'm not sure why this code allocates this string for the error message.
  I think it would be better to always use snprintf and have the format
  limit the size of the name appropriately (like %.200s).

  Klocwork #340
........
  r51227 | neal.norwitz | 2006-08-12 04:06:34 +0200 (Sat, 12 Aug 2006) | 3 lines

  Check returned pointer is valid.
  Klocwork #233
........
  r51228 | neal.norwitz | 2006-08-12 04:12:30 +0200 (Sat, 12 Aug 2006) | 1 line

  Whoops, how did that get in there. :-)  Revert all the parts of 51227 that were not supposed to go it.  Only Modules/_ctypes/cfields.c was supposed to be changed
........
  r51229 | neal.norwitz | 2006-08-12 04:33:36 +0200 (Sat, 12 Aug 2006) | 4 lines

  Don't deref v if it's NULL.

  Klocwork #214
........
  r51230 | neal.norwitz | 2006-08-12 05:16:54 +0200 (Sat, 12 Aug 2006) | 5 lines

  Check return of PyMem_MALLOC (garbage) is non-NULL.
  Check seq in both portions of if/else.

  Klocwork #289-290.
........
  r51231 | neal.norwitz | 2006-08-12 05:17:41 +0200 (Sat, 12 Aug 2006) | 4 lines

  PyModule_GetDict() can fail, produce fatal errors if this happens on startup.

  Klocwork #298-299.
........
  r51232 | neal.norwitz | 2006-08-12 05:18:50 +0200 (Sat, 12 Aug 2006) | 5 lines

  Verify verdat which is returned from malloc is not NULL.
  Ensure we don't pass NULL to free.

  Klocwork #306 (at least the first part, checking malloc)
........
  r51233 | tim.peters | 2006-08-12 06:42:47 +0200 (Sat, 12 Aug 2006) | 35 lines

  test_signal:  Signal handling on the Tru64 buildbot
  appears to be utterly insane.  Plug some theoretical
  insecurities in the test script:

  - Verify that the SIGALRM handler was actually installed.

  - Don't call alarm() before the handler is installed.

  - Move everything that can fail inside the try/finally,
    so the test cleans up after itself more often.

  - Try sending all the expected signals in
    force_test_exit(), not just SIGALRM.  Since that was
    fixed to actually send SIGALRM (instead of invisibly
    dying with an AttributeError), we've seen that sending
    SIGALRM alone does not stop this from hanging.

  - Move the "kill the child" business into the finally
    clause, so the child doesn't survive test failure
    to send SIGALRM to other tests later (there are also
    baffling SIGALRM-related failures in test_socket).

  - Cancel the alarm in the finally clause -- if the
    test dies early, we again don't want SIGALRM showing
    up to confuse a later test.

  Alas, this still relies on timing luck wrt the spawned
  script that sends the test signals, but it's hard to see
  how waiting for seconds can so often be so unlucky.

  test_threadedsignals:  curiously, this test never fails
  on Tru64, but doesn't normally signal SIGALRM.  Anyway,
  fixed an obvious (but probably inconsequential) logic
  error.
........
  r51234 | tim.peters | 2006-08-12 07:17:41 +0200 (Sat, 12 Aug 2006) | 8 lines

  Ah, fudge.  One of the prints here actually "shouldn't be"
  protected by "if verbose:", which caused the test to fail on
  all non-Windows boxes.

  Note that I deliberately didn't convert this to unittest yet,
  because I expect it would be even harder to debug this on Tru64
  after conversion.
........
  r51235 | georg.brandl | 2006-08-12 10:32:02 +0200 (Sat, 12 Aug 2006) | 3 lines

  Repair logging test spew caused by rev. 51206.
........
  r51236 | neal.norwitz | 2006-08-12 19:03:09 +0200 (Sat, 12 Aug 2006) | 8 lines

  Patch #1538606, Patch to fix __index__() clipping.

  I modified this patch some by fixing style, some error checking, and adding
  XXX comments.  This patch requires review and some changes are to be expected.
  I'm checking in now to get the greatest possible review and establish a
  baseline for moving forward.  I don't want this to hold up release if possible.
........
  r51238 | neal.norwitz | 2006-08-12 20:44:06 +0200 (Sat, 12 Aug 2006) | 10 lines

  Fix a couple of bugs exposed by the new __index__ code.  The 64-bit buildbots
  were failing due to inappropriate clipping of numbers larger than 2**31
  with new-style classes. (typeobject.c)  In reviewing the code for classic
  classes, there were 2 problems.  Any negative value return could be returned.
  Always return -1 if there was an error.  Also make the checks similar
  with the new-style classes.  I believe this is correct for 32 and 64 bit
  boxes, including Windows64.

  Add a test of classic classes too.
........
  r51240 | neal.norwitz | 2006-08-13 02:20:49 +0200 (Sun, 13 Aug 2006) | 1 line

  SF bug #1539336, distutils example code missing
........
  r51245 | neal.norwitz | 2006-08-13 20:10:10 +0200 (Sun, 13 Aug 2006) | 6 lines

  Move/copy assert for tstate != NULL before first use.
  Verify that PyEval_Get{Globals,Locals} returned valid pointers.

  Klocwork 231-232
........
  r51246 | neal.norwitz | 2006-08-13 20:10:28 +0200 (Sun, 13 Aug 2006) | 5 lines

  Handle a whole lot of failures from PyString_FromInternedString().

  Should fix most of Klocwork 234-272.
........
  r51247 | neal.norwitz | 2006-08-13 20:10:47 +0200 (Sun, 13 Aug 2006) | 8 lines

  cpathname could be NULL if it was longer than MAXPATHLEN.  Don't try
  to write the .pyc to NULL.

  Check results of PyList_GetItem() and PyModule_GetDict() are not NULL.

  Klocwork 282, 283, 285
........
  r51248 | neal.norwitz | 2006-08-13 20:11:08 +0200 (Sun, 13 Aug 2006) | 6 lines

  Fix segfault when doing string formatting on subclasses of long if
  __oct__, __hex__ don't return a string.

  Klocwork 308
........
  r51250 | neal.norwitz | 2006-08-13 20:11:27 +0200 (Sun, 13 Aug 2006) | 5 lines

  Check return result of PyModule_GetDict().
  Fix a bunch of refleaks in the init of the module.  This would only be found
  when running python -v.
........
  r51251 | neal.norwitz | 2006-08-13 20:11:43 +0200 (Sun, 13 Aug 2006) | 5 lines

  Handle malloc and fopen failures more gracefully.

  Klocwork 180-181
........
  r51252 | neal.norwitz | 2006-08-13 20:12:03 +0200 (Sun, 13 Aug 2006) | 7 lines

  It's very unlikely, though possible that source is not a string.  Verify
  that PyString_AsString() returns a valid pointer.  (The problem can
  arise when zlib.decompress doesn't return a string.)

  Klocwork 346
........
  r51253 | neal.norwitz | 2006-08-13 20:12:26 +0200 (Sun, 13 Aug 2006) | 5 lines

  Handle failures from lookup.

  Klocwork 341-342
........
  r51254 | neal.norwitz | 2006-08-13 20:12:45 +0200 (Sun, 13 Aug 2006) | 6 lines

  Handle failure from PyModule_GetDict() (Klocwork 208).

  Fix a bunch of refleaks in the init of the module.  This would only be found
  when running python -v.
........
  r51255 | neal.norwitz | 2006-08-13 20:13:02 +0200 (Sun, 13 Aug 2006) | 4 lines

  Really address the issue of where to place the assert for leftblock.
  (Followup of Klocwork 274)
........
  r51256 | neal.norwitz | 2006-08-13 20:13:36 +0200 (Sun, 13 Aug 2006) | 4 lines

  Handle malloc failure.

  Klocwork 281
........
  r51258 | neal.norwitz | 2006-08-13 20:40:39 +0200 (Sun, 13 Aug 2006) | 4 lines

  Handle alloca failures.

  Klocwork 225-228
........
  r51259 | neal.norwitz | 2006-08-13 20:41:15 +0200 (Sun, 13 Aug 2006) | 1 line

  Get rid of compiler warning
........
  r51261 | neal.norwitz | 2006-08-14 02:51:15 +0200 (Mon, 14 Aug 2006) | 1 line

  Ignore pgen.exe and kill_python.exe for cygwin
........
  r51262 | neal.norwitz | 2006-08-14 02:59:03 +0200 (Mon, 14 Aug 2006) | 4 lines

  Can't return NULL from a void function.  If there is a memory error,
  about the best we can do is call PyErr_WriteUnraisable and go on.
  We won't be able to do the call below either, so verify delstr is valid.
........
  r51263 | neal.norwitz | 2006-08-14 03:49:54 +0200 (Mon, 14 Aug 2006) | 1 line

  Update purify doc some.
........
  r51264 | thomas.heller | 2006-08-14 09:13:05 +0200 (Mon, 14 Aug 2006) | 2 lines

  Remove unused, buggy test function.
  Fixes klockwork issue #207.
........
  r51265 | thomas.heller | 2006-08-14 09:14:09 +0200 (Mon, 14 Aug 2006) | 2 lines

  Check for NULL return value from new_CArgObject().
  Fixes klockwork issues #183, #184, #185.
........
  r51266 | thomas.heller | 2006-08-14 09:50:14 +0200 (Mon, 14 Aug 2006) | 2 lines

  Check for NULL return value of GenericCData_new().
  Fixes klockwork issues #188, #189.
........
  r51274 | thomas.heller | 2006-08-14 12:02:24 +0200 (Mon, 14 Aug 2006) | 2 lines

  Revert the change that tries to zero out a closure's result storage
  area because the size if unknown in source/callproc.c.
........
  r51276 | marc-andre.lemburg | 2006-08-14 12:55:19 +0200 (Mon, 14 Aug 2006) | 11 lines

  Slightly revised version of patch #1538956:

  Replace UnicodeDecodeErrors raised during == and !=
  compares of Unicode and other objects with a new
  UnicodeWarning.

  All other comparisons continue to raise exceptions.
  Exceptions other than UnicodeDecodeErrors are also left
  untouched.
........
  r51277 | thomas.heller | 2006-08-14 13:17:48 +0200 (Mon, 14 Aug 2006) | 13 lines

  Apply the patch #1532975 plus ideas from the patch #1533481.

  ctypes instances no longer have the internal and undocumented
  '_as_parameter_' attribute which was used to adapt them to foreign
  function calls; this mechanism is replaced by a function pointer in
  the type's stgdict.

  In the 'from_param' class methods, try the _as_parameter_ attribute if
  other conversions are not possible.

  This makes the documented _as_parameter_ mechanism work as intended.

  Change the ctypes version number to 1.0.1.
........
  r51278 | marc-andre.lemburg | 2006-08-14 13:44:34 +0200 (Mon, 14 Aug 2006) | 3 lines

  Readd NEWS items that were accidentally removed by r51276.
........
  r51279 | georg.brandl | 2006-08-14 14:36:06 +0200 (Mon, 14 Aug 2006) | 3 lines

  Improve markup in PyUnicode_RichCompare.
........
  r51280 | marc-andre.lemburg | 2006-08-14 14:57:27 +0200 (Mon, 14 Aug 2006) | 3 lines

  Correct an accidentally removed previous patch.
........
  r51281 | thomas.heller | 2006-08-14 18:17:41 +0200 (Mon, 14 Aug 2006) | 3 lines

  Patch #1536908: Add support for AMD64 / OpenBSD.
  Remove the -no-stack-protector compiler flag for OpenBSD
  as it has been reported to be unneeded.
........
  r51282 | thomas.heller | 2006-08-14 18:20:04 +0200 (Mon, 14 Aug 2006) | 1 line

  News item for rev 51281.
........
  r51283 | georg.brandl | 2006-08-14 22:25:39 +0200 (Mon, 14 Aug 2006) | 3 lines

  Fix refleak introduced in rev. 51248.
........
  r51284 | georg.brandl | 2006-08-14 23:34:08 +0200 (Mon, 14 Aug 2006) | 5 lines

  Make tabnanny recognize IndentationErrors raised by tokenize.
  Add a test to test_inspect to make sure indented source
  is recognized correctly. (fixes #1224621)
........
  r51285 | georg.brandl | 2006-08-14 23:42:55 +0200 (Mon, 14 Aug 2006) | 3 lines

  Patch #1535500: fix segfault in BZ2File.writelines and make sure it
  raises the correct exceptions.
........
  r51287 | georg.brandl | 2006-08-14 23:45:32 +0200 (Mon, 14 Aug 2006) | 3 lines

  Add an additional test: BZ2File write methods should raise IOError
  when file is read-only.
........
  r51289 | georg.brandl | 2006-08-14 23:55:28 +0200 (Mon, 14 Aug 2006) | 3 lines

  Patch #1536071: trace.py should now find the full module name of a
  file correctly even on Windows.
........
  r51290 | georg.brandl | 2006-08-15 00:01:24 +0200 (Tue, 15 Aug 2006) | 3 lines

  Cookie.py shouldn't "bogusly" use string._idmap.
........
  r51291 | georg.brandl | 2006-08-15 00:10:24 +0200 (Tue, 15 Aug 2006) | 3 lines

  Patch #1511317: don't crash on invalid hostname info
........
  r51292 | tim.peters | 2006-08-15 02:25:04 +0200 (Tue, 15 Aug 2006) | 2 lines

  Whitespace normalization.
........
  r51293 | neal.norwitz | 2006-08-15 06:14:57 +0200 (Tue, 15 Aug 2006) | 3 lines

  Georg fixed one of my bugs, so I'll repay him with 2 NEWS entries.
  Now we're even. :-)
........
  r51295 | neal.norwitz | 2006-08-15 06:58:28 +0200 (Tue, 15 Aug 2006) | 8 lines

  Fix the test for SocketServer so it should pass on cygwin and not fail
  sporadically on other platforms.  This is really a band-aid that doesn't
  fix the underlying issue in SocketServer.  It's not clear if it's worth
  it to fix SocketServer, however, I opened a bug to track it:

  	http://python.org/sf/1540386
........
  r51296 | neal.norwitz | 2006-08-15 06:59:30 +0200 (Tue, 15 Aug 2006) | 3 lines

  Update the docstring to use a version a little newer than 1999.  This was
  taken from a Debian patch.  Should we update the version for each release?
........
  r51298 | neal.norwitz | 2006-08-15 08:29:03 +0200 (Tue, 15 Aug 2006) | 2 lines

  Subclasses of int/long are allowed to define an __index__.
........
  r51300 | thomas.heller | 2006-08-15 15:07:21 +0200 (Tue, 15 Aug 2006) | 1 line

  Check for NULL return value from new_CArgObject calls.
........
  r51303 | kurt.kaiser | 2006-08-16 05:15:26 +0200 (Wed, 16 Aug 2006) | 2 lines

  The 'with' statement is now a Code Context block opener
........
  r51304 | anthony.baxter | 2006-08-16 05:42:26 +0200 (Wed, 16 Aug 2006) | 1 line

  preparing for 2.5c1
........
  r51305 | anthony.baxter | 2006-08-16 05:58:37 +0200 (Wed, 16 Aug 2006) | 1 line

  preparing for 2.5c1 - no, really this time
........
  r51306 | kurt.kaiser | 2006-08-16 07:01:42 +0200 (Wed, 16 Aug 2006) | 9 lines

  Patch #1540892: site.py Quitter() class attempts to close sys.stdin
  before raising SystemExit, allowing IDLE to honor quit() and exit().

  M    Lib/site.py
  M    Lib/idlelib/PyShell.py
  M    Lib/idlelib/CREDITS.txt
  M    Lib/idlelib/NEWS.txt
  M    Misc/NEWS
........
  r51307 | ka-ping.yee | 2006-08-16 09:02:50 +0200 (Wed, 16 Aug 2006) | 6 lines

  Update code and tests to support the 'bytes_le' attribute (for
  little-endian byte order on Windows), and to work around clocks
  with low resolution yielding duplicate UUIDs.

  Anthony Baxter has approved this change.
........
  r51308 | kurt.kaiser | 2006-08-16 09:04:17 +0200 (Wed, 16 Aug 2006) | 2 lines

  Get quit() and exit() to work cleanly when not using subprocess.
........
  r51309 | marc-andre.lemburg | 2006-08-16 10:13:26 +0200 (Wed, 16 Aug 2006) | 2 lines

  Revert to having static version numbers again.
........
  r51310 | martin.v.loewis | 2006-08-16 14:55:10 +0200 (Wed, 16 Aug 2006) | 2 lines

  Build _hashlib on Windows. Build OpenSSL with masm assembler code.
  Fixes #1535502.
........
  r51311 | thomas.heller | 2006-08-16 15:03:11 +0200 (Wed, 16 Aug 2006) | 6 lines

  Add commented assert statements to check that the result of
  PyObject_stgdict() and PyType_stgdict() calls are non-NULL before
  dereferencing the result.  Hopefully this fixes what klocwork is
  complaining about.

  Fix a few other nits as well.
........
  r51312 | anthony.baxter | 2006-08-16 15:08:25 +0200 (Wed, 16 Aug 2006) | 1 line

  news entry for 51307
........
  r51313 | andrew.kuchling | 2006-08-16 15:22:20 +0200 (Wed, 16 Aug 2006) | 1 line

  Add UnicodeWarning
........
  r51314 | andrew.kuchling | 2006-08-16 15:41:52 +0200 (Wed, 16 Aug 2006) | 1 line

  Bump document version to 1.0; remove pystone paragraph
........
  r51315 | andrew.kuchling | 2006-08-16 15:51:32 +0200 (Wed, 16 Aug 2006) | 1 line

  Link to docs; remove an XXX comment
........
  r51316 | martin.v.loewis | 2006-08-16 15:58:51 +0200 (Wed, 16 Aug 2006) | 1 line

  Make cl build step compile-only (/c). Remove libs from source list.
........
  r51317 | thomas.heller | 2006-08-16 16:07:44 +0200 (Wed, 16 Aug 2006) | 5 lines

  The __repr__ method of a NULL py_object does no longer raise an
  exception.  Remove a stray '?' character from the exception text
  when the value is retrieved of such an object.

  Includes tests.
........
  r51318 | andrew.kuchling | 2006-08-16 16:18:23 +0200 (Wed, 16 Aug 2006) | 1 line

  Update bug/patch counts
........
  r51319 | andrew.kuchling | 2006-08-16 16:21:14 +0200 (Wed, 16 Aug 2006) | 1 line

  Wording/typo fixes
........
  r51320 | thomas.heller | 2006-08-16 17:10:12 +0200 (Wed, 16 Aug 2006) | 9 lines

  Remove the special casing of Py_None when converting the return value
  of the Python part of a callback function to C.  If it cannot be
  converted, call PyErr_WriteUnraisable with the exception we got.
  Before, arbitrary data has been passed to the calling C code in this
  case.

  (I'm not really sure the NEWS entry is understandable, but I cannot
  find better words)
........
  r51321 | marc-andre.lemburg | 2006-08-16 18:11:01 +0200 (Wed, 16 Aug 2006) | 2 lines

  Add NEWS item mentioning the reverted distutils version number patch.
........
  r51322 | fredrik.lundh | 2006-08-16 18:47:07 +0200 (Wed, 16 Aug 2006) | 5 lines

  SF#1534630

  ignore data that arrives before the opening start tag
........
  r51324 | andrew.kuchling | 2006-08-16 19:11:18 +0200 (Wed, 16 Aug 2006) | 1 line

  Grammar fix
........
  r51328 | thomas.heller | 2006-08-16 20:02:11 +0200 (Wed, 16 Aug 2006) | 12 lines

  Tutorial:

      Clarify somewhat how parameters are passed to functions
      (especially explain what integer means).

      Correct the table - Python integers and longs can both be used.
      Further clarification to the table comparing ctypes types, Python
      types, and C types.

  Reference:

      Replace integer by C ``int`` where it makes sense.
........
  r51329 | kurt.kaiser | 2006-08-16 23:45:59 +0200 (Wed, 16 Aug 2006) | 8 lines

  File menu hotkeys: there were three 'p' assignments.  Reassign the
  'Save Copy As' and 'Print' hotkeys to 'y' and 't'.  Change the
  Shell menu hotkey from 's' to 'l'.

  M    Bindings.py
  M    PyShell.py
  M    NEWS.txt
........
  r51330 | neil.schemenauer | 2006-08-17 01:38:05 +0200 (Thu, 17 Aug 2006) | 3 lines

  Fix a bug in the ``compiler`` package that caused invalid code to be
  generated for generator expressions.
........
  r51342 | martin.v.loewis | 2006-08-17 21:19:32 +0200 (Thu, 17 Aug 2006) | 3 lines

  Merge 51340 and 51341 from 2.5 branch:
  Leave tk build directory to restore original path.
  Invoke debug mk1mf.pl after running Configure.
........
  r51354 | martin.v.loewis | 2006-08-18 05:47:18 +0200 (Fri, 18 Aug 2006) | 3 lines

  Bug #1541863: uuid.uuid1 failed to generate unique identifiers
  on systems with low clock resolution.
........
  r51355 | neal.norwitz | 2006-08-18 05:57:54 +0200 (Fri, 18 Aug 2006) | 1 line

  Add template for 2.6 on HEAD
........
  r51356 | neal.norwitz | 2006-08-18 06:01:38 +0200 (Fri, 18 Aug 2006) | 1 line

  More post-release wibble
........
  r51357 | neal.norwitz | 2006-08-18 06:58:33 +0200 (Fri, 18 Aug 2006) | 1 line

  Try to get Windows bots working again
........
  r51358 | neal.norwitz | 2006-08-18 07:10:00 +0200 (Fri, 18 Aug 2006) | 1 line

  Try to get Windows bots working again. Take 2
........
  r51359 | neal.norwitz | 2006-08-18 07:39:20 +0200 (Fri, 18 Aug 2006) | 1 line

  Try to get Unix bots install working again.
........
  r51360 | neal.norwitz | 2006-08-18 07:41:46 +0200 (Fri, 18 Aug 2006) | 1 line

  Set version to 2.6a0, seems more consistent.
........
  r51362 | neal.norwitz | 2006-08-18 08:14:52 +0200 (Fri, 18 Aug 2006) | 1 line

  More version wibble
........
  r51364 | georg.brandl | 2006-08-18 09:27:59 +0200 (Fri, 18 Aug 2006) | 4 lines

  Bug #1541682: Fix example in the "Refcount details" API docs.
  Additionally, remove a faulty example showing PySequence_SetItem applied
  to a newly created list object and add notes that this isn't a good idea.
........
  r51366 | anthony.baxter | 2006-08-18 09:29:02 +0200 (Fri, 18 Aug 2006) | 3 lines

  Updating IDLE's version number to match Python's (as per python-dev
  discussion).
........
  r51367 | anthony.baxter | 2006-08-18 09:30:07 +0200 (Fri, 18 Aug 2006) | 1 line

  RPM specfile updates
........
  r51368 | georg.brandl | 2006-08-18 09:35:47 +0200 (Fri, 18 Aug 2006) | 2 lines

  Typo in tp_clear docs.
........
  r51378 | andrew.kuchling | 2006-08-18 15:57:13 +0200 (Fri, 18 Aug 2006) | 1 line

  Minor edits
........
  r51379 | thomas.heller | 2006-08-18 16:38:46 +0200 (Fri, 18 Aug 2006) | 6 lines

  Add asserts to check for 'impossible' NULL values, with comments.
  In one place where I'n not 1000% sure about the non-NULL, raise
  a RuntimeError for safety.

  This should fix the klocwork issues that Neal sent me.  If so,
  it should be applied to the release25-maint branch also.
........
  r51400 | neal.norwitz | 2006-08-19 06:22:33 +0200 (Sat, 19 Aug 2006) | 5 lines

  Move initialization of interned strings to before allocating the
  object so we don't leak op.  (Fixes an earlier patch to this code)

  Klockwork #350
........
  r51401 | neal.norwitz | 2006-08-19 06:23:04 +0200 (Sat, 19 Aug 2006) | 4 lines

  Move assert to after NULL check, otherwise we deref NULL in the assert.

  Klocwork #307
........
  r51402 | neal.norwitz | 2006-08-19 06:25:29 +0200 (Sat, 19 Aug 2006) | 2 lines

  SF #1542693: Remove semi-colon at end of PyImport_ImportModuleEx macro
........
  r51403 | neal.norwitz | 2006-08-19 06:28:55 +0200 (Sat, 19 Aug 2006) | 6 lines

  Move initialization to after the asserts for non-NULL values.

  Klocwork 286-287.

  (I'm not backporting this, but if someone wants to, feel free.)
........
  r51404 | neal.norwitz | 2006-08-19 06:52:03 +0200 (Sat, 19 Aug 2006) | 6 lines

  Handle PyString_FromInternedString() failing (unlikely, but possible).

  Klocwork #325

  (I'm not backporting this, but if someone wants to, feel free.)
........
  r51416 | georg.brandl | 2006-08-20 15:15:39 +0200 (Sun, 20 Aug 2006) | 2 lines

  Patch #1542948: fix urllib2 header casing issue. With new test.
........
  r51428 | jeremy.hylton | 2006-08-21 18:19:37 +0200 (Mon, 21 Aug 2006) | 3 lines

  Move peephole optimizer to separate file.
........
  r51429 | jeremy.hylton | 2006-08-21 18:20:29 +0200 (Mon, 21 Aug 2006) | 2 lines

  Move peephole optimizer to separate file.  (Forgot .h in previous checkin.)
........
  r51432 | neal.norwitz | 2006-08-21 19:59:46 +0200 (Mon, 21 Aug 2006) | 5 lines

  Fix bug #1543303, tarfile adds padding that breaks gunzip.
  Patch # 1543897.

  Will backport to 2.5
........
  r51433 | neal.norwitz | 2006-08-21 20:01:30 +0200 (Mon, 21 Aug 2006) | 2 lines

  Add assert to make Klocwork happy (#276)
........
2006-08-21 19:07:27 +00:00

2151 lines
58 KiB
C

/*
* New exceptions.c written in Iceland by Richard Jones and Georg Brandl.
*
* Thanks go to Tim Peters and Michael Hudson for debugging.
*/
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "structmember.h"
#include "osdefs.h"
#define MAKE_IT_NONE(x) (x) = Py_None; Py_INCREF(Py_None);
#define EXC_MODULE_NAME "exceptions."
/* NOTE: If the exception class hierarchy changes, don't forget to update
* Lib/test/exception_hierarchy.txt
*/
PyDoc_STRVAR(exceptions_doc, "Python's standard exception class hierarchy.\n\
\n\
Exceptions found here are defined both in the exceptions module and the\n\
built-in namespace. It is recommended that user-defined exceptions\n\
inherit from Exception. See the documentation for the exception\n\
inheritance hierarchy.\n\
");
/*
* BaseException
*/
static PyObject *
BaseException_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyBaseExceptionObject *self;
self = (PyBaseExceptionObject *)type->tp_alloc(type, 0);
/* the dict is created on the fly in PyObject_GenericSetAttr */
self->message = self->dict = NULL;
self->args = PyTuple_New(0);
if (!self->args) {
Py_DECREF(self);
return NULL;
}
self->message = PyString_FromString("");
if (!self->message) {
Py_DECREF(self);
return NULL;
}
return (PyObject *)self;
}
static int
BaseException_init(PyBaseExceptionObject *self, PyObject *args, PyObject *kwds)
{
if (!_PyArg_NoKeywords(self->ob_type->tp_name, kwds))
return -1;
Py_DECREF(self->args);
self->args = args;
Py_INCREF(self->args);
if (PyTuple_GET_SIZE(self->args) == 1) {
Py_CLEAR(self->message);
self->message = PyTuple_GET_ITEM(self->args, 0);
Py_INCREF(self->message);
}
return 0;
}
static int
BaseException_clear(PyBaseExceptionObject *self)
{
Py_CLEAR(self->dict);
Py_CLEAR(self->args);
Py_CLEAR(self->message);
return 0;
}
static void
BaseException_dealloc(PyBaseExceptionObject *self)
{
BaseException_clear(self);
self->ob_type->tp_free((PyObject *)self);
}
static int
BaseException_traverse(PyBaseExceptionObject *self, visitproc visit, void *arg)
{
Py_VISIT(self->dict);
Py_VISIT(self->args);
Py_VISIT(self->message);
return 0;
}
static PyObject *
BaseException_str(PyBaseExceptionObject *self)
{
PyObject *out;
switch (PyTuple_GET_SIZE(self->args)) {
case 0:
out = PyString_FromString("");
break;
case 1:
out = PyObject_Str(PyTuple_GET_ITEM(self->args, 0));
break;
default:
out = PyObject_Str(self->args);
break;
}
return out;
}
static PyObject *
BaseException_repr(PyBaseExceptionObject *self)
{
PyObject *repr_suffix;
PyObject *repr;
char *name;
char *dot;
repr_suffix = PyObject_Repr(self->args);
if (!repr_suffix)
return NULL;
name = (char *)self->ob_type->tp_name;
dot = strrchr(name, '.');
if (dot != NULL) name = dot+1;
repr = PyString_FromString(name);
if (!repr) {
Py_DECREF(repr_suffix);
return NULL;
}
PyString_ConcatAndDel(&repr, repr_suffix);
return repr;
}
/* Pickling support */
static PyObject *
BaseException_reduce(PyBaseExceptionObject *self)
{
if (self->args && self->dict)
return PyTuple_Pack(3, self->ob_type, self->args, self->dict);
else
return PyTuple_Pack(2, self->ob_type, self->args);
}
/*
* Needed for backward compatibility, since exceptions used to store
* all their attributes in the __dict__. Code is taken from cPickle's
* load_build function.
*/
static PyObject *
BaseException_setstate(PyObject *self, PyObject *state)
{
PyObject *d_key, *d_value;
Py_ssize_t i = 0;
if (state != Py_None) {
if (!PyDict_Check(state)) {
PyErr_SetString(PyExc_TypeError, "state is not a dictionary");
return NULL;
}
while (PyDict_Next(state, &i, &d_key, &d_value)) {
if (PyObject_SetAttr(self, d_key, d_value) < 0)
return NULL;
}
}
Py_RETURN_NONE;
}
#ifdef Py_USING_UNICODE
/* while this method generates fairly uninspired output, it a least
* guarantees that we can display exceptions that have unicode attributes
*/
static PyObject *
BaseException_unicode(PyBaseExceptionObject *self)
{
if (PyTuple_GET_SIZE(self->args) == 0)
return PyUnicode_FromUnicode(NULL, 0);
if (PyTuple_GET_SIZE(self->args) == 1)
return PyObject_Unicode(PyTuple_GET_ITEM(self->args, 0));
return PyObject_Unicode(self->args);
}
#endif /* Py_USING_UNICODE */
static PyMethodDef BaseException_methods[] = {
{"__reduce__", (PyCFunction)BaseException_reduce, METH_NOARGS },
{"__setstate__", (PyCFunction)BaseException_setstate, METH_O },
#ifdef Py_USING_UNICODE
{"__unicode__", (PyCFunction)BaseException_unicode, METH_NOARGS },
#endif
{NULL, NULL, 0, NULL},
};
static PyObject *
BaseException_getitem(PyBaseExceptionObject *self, Py_ssize_t index)
{
return PySequence_GetItem(self->args, index);
}
static PySequenceMethods BaseException_as_sequence = {
0, /* sq_length; */
0, /* sq_concat; */
0, /* sq_repeat; */
(ssizeargfunc)BaseException_getitem, /* sq_item; */
0, /* sq_slice; */
0, /* sq_ass_item; */
0, /* sq_ass_slice; */
0, /* sq_contains; */
0, /* sq_inplace_concat; */
0 /* sq_inplace_repeat; */
};
static PyMemberDef BaseException_members[] = {
{"message", T_OBJECT, offsetof(PyBaseExceptionObject, message), 0,
PyDoc_STR("exception message")},
{NULL} /* Sentinel */
};
static PyObject *
BaseException_get_dict(PyBaseExceptionObject *self)
{
if (self->dict == NULL) {
self->dict = PyDict_New();
if (!self->dict)
return NULL;
}
Py_INCREF(self->dict);
return self->dict;
}
static int
BaseException_set_dict(PyBaseExceptionObject *self, PyObject *val)
{
if (val == NULL) {
PyErr_SetString(PyExc_TypeError, "__dict__ may not be deleted");
return -1;
}
if (!PyDict_Check(val)) {
PyErr_SetString(PyExc_TypeError, "__dict__ must be a dictionary");
return -1;
}
Py_CLEAR(self->dict);
Py_INCREF(val);
self->dict = val;
return 0;
}
static PyObject *
BaseException_get_args(PyBaseExceptionObject *self)
{
if (self->args == NULL) {
Py_INCREF(Py_None);
return Py_None;
}
Py_INCREF(self->args);
return self->args;
}
static int
BaseException_set_args(PyBaseExceptionObject *self, PyObject *val)
{
PyObject *seq;
if (val == NULL) {
PyErr_SetString(PyExc_TypeError, "args may not be deleted");
return -1;
}
seq = PySequence_Tuple(val);
if (!seq) return -1;
Py_CLEAR(self->args);
self->args = seq;
return 0;
}
static PyGetSetDef BaseException_getset[] = {
{"__dict__", (getter)BaseException_get_dict, (setter)BaseException_set_dict},
{"args", (getter)BaseException_get_args, (setter)BaseException_set_args},
{NULL},
};
static PyTypeObject _PyExc_BaseException = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
EXC_MODULE_NAME "BaseException", /*tp_name*/
sizeof(PyBaseExceptionObject), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)BaseException_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /* tp_compare; */
(reprfunc)BaseException_repr, /*tp_repr*/
0, /*tp_as_number*/
&BaseException_as_sequence, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
(reprfunc)BaseException_str, /*tp_str*/
PyObject_GenericGetAttr, /*tp_getattro*/
PyObject_GenericSetAttr, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
PyDoc_STR("Common base class for all exceptions"), /* tp_doc */
(traverseproc)BaseException_traverse, /* tp_traverse */
(inquiry)BaseException_clear, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
BaseException_methods, /* tp_methods */
BaseException_members, /* tp_members */
BaseException_getset, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
offsetof(PyBaseExceptionObject, dict), /* tp_dictoffset */
(initproc)BaseException_init, /* tp_init */
0, /* tp_alloc */
BaseException_new, /* tp_new */
};
/* the CPython API expects exceptions to be (PyObject *) - both a hold-over
from the previous implmentation and also allowing Python objects to be used
in the API */
PyObject *PyExc_BaseException = (PyObject *)&_PyExc_BaseException;
/* note these macros omit the last semicolon so the macro invocation may
* include it and not look strange.
*/
#define SimpleExtendsException(EXCBASE, EXCNAME, EXCDOC) \
static PyTypeObject _PyExc_ ## EXCNAME = { \
PyObject_HEAD_INIT(NULL) \
0, \
EXC_MODULE_NAME # EXCNAME, \
sizeof(PyBaseExceptionObject), \
0, (destructor)BaseException_dealloc, 0, 0, 0, 0, 0, 0, 0, \
0, 0, 0, 0, 0, 0, 0, \
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
PyDoc_STR(EXCDOC), (traverseproc)BaseException_traverse, \
(inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
0, 0, 0, offsetof(PyBaseExceptionObject, dict), \
(initproc)BaseException_init, 0, BaseException_new,\
}; \
PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
#define MiddlingExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDOC) \
static PyTypeObject _PyExc_ ## EXCNAME = { \
PyObject_HEAD_INIT(NULL) \
0, \
EXC_MODULE_NAME # EXCNAME, \
sizeof(Py ## EXCSTORE ## Object), \
0, (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
0, 0, 0, 0, 0, \
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
(inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
(initproc)EXCSTORE ## _init, 0, BaseException_new,\
}; \
PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
#define ComplexExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDEALLOC, EXCMETHODS, EXCMEMBERS, EXCSTR, EXCDOC) \
static PyTypeObject _PyExc_ ## EXCNAME = { \
PyObject_HEAD_INIT(NULL) \
0, \
EXC_MODULE_NAME # EXCNAME, \
sizeof(Py ## EXCSTORE ## Object), 0, \
(destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
(reprfunc)EXCSTR, 0, 0, 0, \
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
(inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, EXCMETHODS, \
EXCMEMBERS, 0, &_ ## EXCBASE, \
0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
(initproc)EXCSTORE ## _init, 0, BaseException_new,\
}; \
PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
/*
* Exception extends BaseException
*/
SimpleExtendsException(PyExc_BaseException, Exception,
"Common base class for all non-exit exceptions.");
/*
* StandardError extends Exception
*/
SimpleExtendsException(PyExc_Exception, StandardError,
"Base class for all standard Python exceptions that do not represent\n"
"interpreter exiting.");
/*
* TypeError extends StandardError
*/
SimpleExtendsException(PyExc_StandardError, TypeError,
"Inappropriate argument type.");
/*
* StopIteration extends Exception
*/
SimpleExtendsException(PyExc_Exception, StopIteration,
"Signal the end from iterator.next().");
/*
* GeneratorExit extends Exception
*/
SimpleExtendsException(PyExc_Exception, GeneratorExit,
"Request that a generator exit.");
/*
* SystemExit extends BaseException
*/
static int
SystemExit_init(PySystemExitObject *self, PyObject *args, PyObject *kwds)
{
Py_ssize_t size = PyTuple_GET_SIZE(args);
if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
return -1;
if (size == 0)
return 0;
Py_CLEAR(self->code);
if (size == 1)
self->code = PyTuple_GET_ITEM(args, 0);
else if (size > 1)
self->code = args;
Py_INCREF(self->code);
return 0;
}
static int
SystemExit_clear(PySystemExitObject *self)
{
Py_CLEAR(self->code);
return BaseException_clear((PyBaseExceptionObject *)self);
}
static void
SystemExit_dealloc(PySystemExitObject *self)
{
SystemExit_clear(self);
self->ob_type->tp_free((PyObject *)self);
}
static int
SystemExit_traverse(PySystemExitObject *self, visitproc visit, void *arg)
{
Py_VISIT(self->code);
return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
}
static PyMemberDef SystemExit_members[] = {
{"message", T_OBJECT, offsetof(PySystemExitObject, message), 0,
PyDoc_STR("exception message")},
{"code", T_OBJECT, offsetof(PySystemExitObject, code), 0,
PyDoc_STR("exception code")},
{NULL} /* Sentinel */
};
ComplexExtendsException(PyExc_BaseException, SystemExit, SystemExit,
SystemExit_dealloc, 0, SystemExit_members, 0,
"Request to exit from the interpreter.");
/*
* KeyboardInterrupt extends BaseException
*/
SimpleExtendsException(PyExc_BaseException, KeyboardInterrupt,
"Program interrupted by user.");
/*
* ImportError extends StandardError
*/
SimpleExtendsException(PyExc_StandardError, ImportError,
"Import can't find module, or can't find name in module.");
/*
* EnvironmentError extends StandardError
*/
/* Where a function has a single filename, such as open() or some
* of the os module functions, PyErr_SetFromErrnoWithFilename() is
* called, giving a third argument which is the filename. But, so
* that old code using in-place unpacking doesn't break, e.g.:
*
* except IOError, (errno, strerror):
*
* we hack args so that it only contains two items. This also
* means we need our own __str__() which prints out the filename
* when it was supplied.
*/
static int
EnvironmentError_init(PyEnvironmentErrorObject *self, PyObject *args,
PyObject *kwds)
{
PyObject *myerrno = NULL, *strerror = NULL, *filename = NULL;
PyObject *subslice = NULL;
if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
return -1;
if (PyTuple_GET_SIZE(args) <= 1) {
return 0;
}
if (!PyArg_UnpackTuple(args, "EnvironmentError", 2, 3,
&myerrno, &strerror, &filename)) {
return -1;
}
Py_CLEAR(self->myerrno); /* replacing */
self->myerrno = myerrno;
Py_INCREF(self->myerrno);
Py_CLEAR(self->strerror); /* replacing */
self->strerror = strerror;
Py_INCREF(self->strerror);
/* self->filename will remain Py_None otherwise */
if (filename != NULL) {
Py_CLEAR(self->filename); /* replacing */
self->filename = filename;
Py_INCREF(self->filename);
subslice = PyTuple_GetSlice(args, 0, 2);
if (!subslice)
return -1;
Py_DECREF(self->args); /* replacing args */
self->args = subslice;
}
return 0;
}
static int
EnvironmentError_clear(PyEnvironmentErrorObject *self)
{
Py_CLEAR(self->myerrno);
Py_CLEAR(self->strerror);
Py_CLEAR(self->filename);
return BaseException_clear((PyBaseExceptionObject *)self);
}
static void
EnvironmentError_dealloc(PyEnvironmentErrorObject *self)
{
EnvironmentError_clear(self);
self->ob_type->tp_free((PyObject *)self);
}
static int
EnvironmentError_traverse(PyEnvironmentErrorObject *self, visitproc visit,
void *arg)
{
Py_VISIT(self->myerrno);
Py_VISIT(self->strerror);
Py_VISIT(self->filename);
return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
}
static PyObject *
EnvironmentError_str(PyEnvironmentErrorObject *self)
{
PyObject *rtnval = NULL;
if (self->filename) {
PyObject *fmt;
PyObject *repr;
PyObject *tuple;
fmt = PyString_FromString("[Errno %s] %s: %s");
if (!fmt)
return NULL;
repr = PyObject_Repr(self->filename);
if (!repr) {
Py_DECREF(fmt);
return NULL;
}
tuple = PyTuple_New(3);
if (!tuple) {
Py_DECREF(repr);
Py_DECREF(fmt);
return NULL;
}
if (self->myerrno) {
Py_INCREF(self->myerrno);
PyTuple_SET_ITEM(tuple, 0, self->myerrno);
}
else {
Py_INCREF(Py_None);
PyTuple_SET_ITEM(tuple, 0, Py_None);
}
if (self->strerror) {
Py_INCREF(self->strerror);
PyTuple_SET_ITEM(tuple, 1, self->strerror);
}
else {
Py_INCREF(Py_None);
PyTuple_SET_ITEM(tuple, 1, Py_None);
}
PyTuple_SET_ITEM(tuple, 2, repr);
rtnval = PyString_Format(fmt, tuple);
Py_DECREF(fmt);
Py_DECREF(tuple);
}
else if (self->myerrno && self->strerror) {
PyObject *fmt;
PyObject *tuple;
fmt = PyString_FromString("[Errno %s] %s");
if (!fmt)
return NULL;
tuple = PyTuple_New(2);
if (!tuple) {
Py_DECREF(fmt);
return NULL;
}
if (self->myerrno) {
Py_INCREF(self->myerrno);
PyTuple_SET_ITEM(tuple, 0, self->myerrno);
}
else {
Py_INCREF(Py_None);
PyTuple_SET_ITEM(tuple, 0, Py_None);
}
if (self->strerror) {
Py_INCREF(self->strerror);
PyTuple_SET_ITEM(tuple, 1, self->strerror);
}
else {
Py_INCREF(Py_None);
PyTuple_SET_ITEM(tuple, 1, Py_None);
}
rtnval = PyString_Format(fmt, tuple);
Py_DECREF(fmt);
Py_DECREF(tuple);
}
else
rtnval = BaseException_str((PyBaseExceptionObject *)self);
return rtnval;
}
static PyMemberDef EnvironmentError_members[] = {
{"message", T_OBJECT, offsetof(PyEnvironmentErrorObject, message), 0,
PyDoc_STR("exception message")},
{"errno", T_OBJECT, offsetof(PyEnvironmentErrorObject, myerrno), 0,
PyDoc_STR("exception errno")},
{"strerror", T_OBJECT, offsetof(PyEnvironmentErrorObject, strerror), 0,
PyDoc_STR("exception strerror")},
{"filename", T_OBJECT, offsetof(PyEnvironmentErrorObject, filename), 0,
PyDoc_STR("exception filename")},
{NULL} /* Sentinel */
};
static PyObject *
EnvironmentError_reduce(PyEnvironmentErrorObject *self)
{
PyObject *args = self->args;
PyObject *res = NULL, *tmp;
/* self->args is only the first two real arguments if there was a
* file name given to EnvironmentError. */
if (PyTuple_GET_SIZE(args) == 2 && self->filename) {
args = PyTuple_New(3);
if (!args) return NULL;
tmp = PyTuple_GET_ITEM(self->args, 0);
Py_INCREF(tmp);
PyTuple_SET_ITEM(args, 0, tmp);
tmp = PyTuple_GET_ITEM(self->args, 1);
Py_INCREF(tmp);
PyTuple_SET_ITEM(args, 1, tmp);
Py_INCREF(self->filename);
PyTuple_SET_ITEM(args, 2, self->filename);
} else
Py_INCREF(args);
if (self->dict)
res = PyTuple_Pack(3, self->ob_type, args, self->dict);
else
res = PyTuple_Pack(2, self->ob_type, args);
Py_DECREF(args);
return res;
}
static PyMethodDef EnvironmentError_methods[] = {
{"__reduce__", (PyCFunction)EnvironmentError_reduce, METH_NOARGS},
{NULL}
};
ComplexExtendsException(PyExc_StandardError, EnvironmentError,
EnvironmentError, EnvironmentError_dealloc,
EnvironmentError_methods, EnvironmentError_members,
EnvironmentError_str,
"Base class for I/O related errors.");
/*
* IOError extends EnvironmentError
*/
MiddlingExtendsException(PyExc_EnvironmentError, IOError,
EnvironmentError, "I/O operation failed.");
/*
* OSError extends EnvironmentError
*/
MiddlingExtendsException(PyExc_EnvironmentError, OSError,
EnvironmentError, "OS system call failed.");
/*
* WindowsError extends OSError
*/
#ifdef MS_WINDOWS
#include "errmap.h"
static int
WindowsError_clear(PyWindowsErrorObject *self)
{
Py_CLEAR(self->myerrno);
Py_CLEAR(self->strerror);
Py_CLEAR(self->filename);
Py_CLEAR(self->winerror);
return BaseException_clear((PyBaseExceptionObject *)self);
}
static void
WindowsError_dealloc(PyWindowsErrorObject *self)
{
WindowsError_clear(self);
self->ob_type->tp_free((PyObject *)self);
}
static int
WindowsError_traverse(PyWindowsErrorObject *self, visitproc visit, void *arg)
{
Py_VISIT(self->myerrno);
Py_VISIT(self->strerror);
Py_VISIT(self->filename);
Py_VISIT(self->winerror);
return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
}
static int
WindowsError_init(PyWindowsErrorObject *self, PyObject *args, PyObject *kwds)
{
PyObject *o_errcode = NULL;
long errcode;
long posix_errno;
if (EnvironmentError_init((PyEnvironmentErrorObject *)self, args, kwds)
== -1)
return -1;
if (self->myerrno == NULL)
return 0;
/* Set errno to the POSIX errno, and winerror to the Win32
error code. */
errcode = PyInt_AsLong(self->myerrno);
if (errcode == -1 && PyErr_Occurred())
return -1;
posix_errno = winerror_to_errno(errcode);
Py_CLEAR(self->winerror);
self->winerror = self->myerrno;
o_errcode = PyInt_FromLong(posix_errno);
if (!o_errcode)
return -1;
self->myerrno = o_errcode;
return 0;
}
static PyObject *
WindowsError_str(PyWindowsErrorObject *self)
{
PyObject *rtnval = NULL;
if (self->filename) {
PyObject *fmt;
PyObject *repr;
PyObject *tuple;
fmt = PyString_FromString("[Error %s] %s: %s");
if (!fmt)
return NULL;
repr = PyObject_Repr(self->filename);
if (!repr) {
Py_DECREF(fmt);
return NULL;
}
tuple = PyTuple_New(3);
if (!tuple) {
Py_DECREF(repr);
Py_DECREF(fmt);
return NULL;
}
if (self->myerrno) {
Py_INCREF(self->myerrno);
PyTuple_SET_ITEM(tuple, 0, self->myerrno);
}
else {
Py_INCREF(Py_None);
PyTuple_SET_ITEM(tuple, 0, Py_None);
}
if (self->strerror) {
Py_INCREF(self->strerror);
PyTuple_SET_ITEM(tuple, 1, self->strerror);
}
else {
Py_INCREF(Py_None);
PyTuple_SET_ITEM(tuple, 1, Py_None);
}
PyTuple_SET_ITEM(tuple, 2, repr);
rtnval = PyString_Format(fmt, tuple);
Py_DECREF(fmt);
Py_DECREF(tuple);
}
else if (self->myerrno && self->strerror) {
PyObject *fmt;
PyObject *tuple;
fmt = PyString_FromString("[Error %s] %s");
if (!fmt)
return NULL;
tuple = PyTuple_New(2);
if (!tuple) {
Py_DECREF(fmt);
return NULL;
}
if (self->myerrno) {
Py_INCREF(self->myerrno);
PyTuple_SET_ITEM(tuple, 0, self->myerrno);
}
else {
Py_INCREF(Py_None);
PyTuple_SET_ITEM(tuple, 0, Py_None);
}
if (self->strerror) {
Py_INCREF(self->strerror);
PyTuple_SET_ITEM(tuple, 1, self->strerror);
}
else {
Py_INCREF(Py_None);
PyTuple_SET_ITEM(tuple, 1, Py_None);
}
rtnval = PyString_Format(fmt, tuple);
Py_DECREF(fmt);
Py_DECREF(tuple);
}
else
rtnval = EnvironmentError_str((PyEnvironmentErrorObject *)self);
return rtnval;
}
static PyMemberDef WindowsError_members[] = {
{"message", T_OBJECT, offsetof(PyWindowsErrorObject, message), 0,
PyDoc_STR("exception message")},
{"errno", T_OBJECT, offsetof(PyWindowsErrorObject, myerrno), 0,
PyDoc_STR("POSIX exception code")},
{"strerror", T_OBJECT, offsetof(PyWindowsErrorObject, strerror), 0,
PyDoc_STR("exception strerror")},
{"filename", T_OBJECT, offsetof(PyWindowsErrorObject, filename), 0,
PyDoc_STR("exception filename")},
{"winerror", T_OBJECT, offsetof(PyWindowsErrorObject, winerror), 0,
PyDoc_STR("Win32 exception code")},
{NULL} /* Sentinel */
};
ComplexExtendsException(PyExc_OSError, WindowsError, WindowsError,
WindowsError_dealloc, 0, WindowsError_members,
WindowsError_str, "MS-Windows OS system call failed.");
#endif /* MS_WINDOWS */
/*
* VMSError extends OSError (I think)
*/
#ifdef __VMS
MiddlingExtendsException(PyExc_OSError, VMSError, EnvironmentError,
"OpenVMS OS system call failed.");
#endif
/*
* EOFError extends StandardError
*/
SimpleExtendsException(PyExc_StandardError, EOFError,
"Read beyond end of file.");
/*
* RuntimeError extends StandardError
*/
SimpleExtendsException(PyExc_StandardError, RuntimeError,
"Unspecified run-time error.");
/*
* NotImplementedError extends RuntimeError
*/
SimpleExtendsException(PyExc_RuntimeError, NotImplementedError,
"Method or function hasn't been implemented yet.");
/*
* NameError extends StandardError
*/
SimpleExtendsException(PyExc_StandardError, NameError,
"Name not found globally.");
/*
* UnboundLocalError extends NameError
*/
SimpleExtendsException(PyExc_NameError, UnboundLocalError,
"Local name referenced but not bound to a value.");
/*
* AttributeError extends StandardError
*/
SimpleExtendsException(PyExc_StandardError, AttributeError,
"Attribute not found.");
/*
* SyntaxError extends StandardError
*/
static int
SyntaxError_init(PySyntaxErrorObject *self, PyObject *args, PyObject *kwds)
{
PyObject *info = NULL;
Py_ssize_t lenargs = PyTuple_GET_SIZE(args);
if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
return -1;
if (lenargs >= 1) {
Py_CLEAR(self->msg);
self->msg = PyTuple_GET_ITEM(args, 0);
Py_INCREF(self->msg);
}
if (lenargs == 2) {
info = PyTuple_GET_ITEM(args, 1);
info = PySequence_Tuple(info);
if (!info) return -1;
if (PyTuple_GET_SIZE(info) != 4) {
/* not a very good error message, but it's what Python 2.4 gives */
PyErr_SetString(PyExc_IndexError, "tuple index out of range");
Py_DECREF(info);
return -1;
}
Py_CLEAR(self->filename);
self->filename = PyTuple_GET_ITEM(info, 0);
Py_INCREF(self->filename);
Py_CLEAR(self->lineno);
self->lineno = PyTuple_GET_ITEM(info, 1);
Py_INCREF(self->lineno);
Py_CLEAR(self->offset);
self->offset = PyTuple_GET_ITEM(info, 2);
Py_INCREF(self->offset);
Py_CLEAR(self->text);
self->text = PyTuple_GET_ITEM(info, 3);
Py_INCREF(self->text);
Py_DECREF(info);
}
return 0;
}
static int
SyntaxError_clear(PySyntaxErrorObject *self)
{
Py_CLEAR(self->msg);
Py_CLEAR(self->filename);
Py_CLEAR(self->lineno);
Py_CLEAR(self->offset);
Py_CLEAR(self->text);
Py_CLEAR(self->print_file_and_line);
return BaseException_clear((PyBaseExceptionObject *)self);
}
static void
SyntaxError_dealloc(PySyntaxErrorObject *self)
{
SyntaxError_clear(self);
self->ob_type->tp_free((PyObject *)self);
}
static int
SyntaxError_traverse(PySyntaxErrorObject *self, visitproc visit, void *arg)
{
Py_VISIT(self->msg);
Py_VISIT(self->filename);
Py_VISIT(self->lineno);
Py_VISIT(self->offset);
Py_VISIT(self->text);
Py_VISIT(self->print_file_and_line);
return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
}
/* This is called "my_basename" instead of just "basename" to avoid name
conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
defined, and Python does define that. */
static char *
my_basename(char *name)
{
char *cp = name;
char *result = name;
if (name == NULL)
return "???";
while (*cp != '\0') {
if (*cp == SEP)
result = cp + 1;
++cp;
}
return result;
}
static PyObject *
SyntaxError_str(PySyntaxErrorObject *self)
{
PyObject *str;
PyObject *result;
int have_filename = 0;
int have_lineno = 0;
char *buffer = NULL;
Py_ssize_t bufsize;
if (self->msg)
str = PyObject_Str(self->msg);
else
str = PyObject_Str(Py_None);
if (!str) return NULL;
/* Don't fiddle with non-string return (shouldn't happen anyway) */
if (!PyString_Check(str)) return str;
/* XXX -- do all the additional formatting with filename and
lineno here */
have_filename = (self->filename != NULL) &&
PyString_Check(self->filename);
have_lineno = (self->lineno != NULL) && PyInt_Check(self->lineno);
if (!have_filename && !have_lineno)
return str;
bufsize = PyString_GET_SIZE(str) + 64;
if (have_filename)
bufsize += PyString_GET_SIZE(self->filename);
buffer = PyMem_MALLOC(bufsize);
if (buffer == NULL)
return str;
if (have_filename && have_lineno)
PyOS_snprintf(buffer, bufsize, "%s (%s, line %ld)",
PyString_AS_STRING(str),
my_basename(PyString_AS_STRING(self->filename)),
PyInt_AsLong(self->lineno));
else if (have_filename)
PyOS_snprintf(buffer, bufsize, "%s (%s)",
PyString_AS_STRING(str),
my_basename(PyString_AS_STRING(self->filename)));
else /* only have_lineno */
PyOS_snprintf(buffer, bufsize, "%s (line %ld)",
PyString_AS_STRING(str),
PyInt_AsLong(self->lineno));
result = PyString_FromString(buffer);
PyMem_FREE(buffer);
if (result == NULL)
result = str;
else
Py_DECREF(str);
return result;
}
static PyMemberDef SyntaxError_members[] = {
{"message", T_OBJECT, offsetof(PySyntaxErrorObject, message), 0,
PyDoc_STR("exception message")},
{"msg", T_OBJECT, offsetof(PySyntaxErrorObject, msg), 0,
PyDoc_STR("exception msg")},
{"filename", T_OBJECT, offsetof(PySyntaxErrorObject, filename), 0,
PyDoc_STR("exception filename")},
{"lineno", T_OBJECT, offsetof(PySyntaxErrorObject, lineno), 0,
PyDoc_STR("exception lineno")},
{"offset", T_OBJECT, offsetof(PySyntaxErrorObject, offset), 0,
PyDoc_STR("exception offset")},
{"text", T_OBJECT, offsetof(PySyntaxErrorObject, text), 0,
PyDoc_STR("exception text")},
{"print_file_and_line", T_OBJECT,
offsetof(PySyntaxErrorObject, print_file_and_line), 0,
PyDoc_STR("exception print_file_and_line")},
{NULL} /* Sentinel */
};
ComplexExtendsException(PyExc_StandardError, SyntaxError, SyntaxError,
SyntaxError_dealloc, 0, SyntaxError_members,
SyntaxError_str, "Invalid syntax.");
/*
* IndentationError extends SyntaxError
*/
MiddlingExtendsException(PyExc_SyntaxError, IndentationError, SyntaxError,
"Improper indentation.");
/*
* TabError extends IndentationError
*/
MiddlingExtendsException(PyExc_IndentationError, TabError, SyntaxError,
"Improper mixture of spaces and tabs.");
/*
* LookupError extends StandardError
*/
SimpleExtendsException(PyExc_StandardError, LookupError,
"Base class for lookup errors.");
/*
* IndexError extends LookupError
*/
SimpleExtendsException(PyExc_LookupError, IndexError,
"Sequence index out of range.");
/*
* KeyError extends LookupError
*/
static PyObject *
KeyError_str(PyBaseExceptionObject *self)
{
/* If args is a tuple of exactly one item, apply repr to args[0].
This is done so that e.g. the exception raised by {}[''] prints
KeyError: ''
rather than the confusing
KeyError
alone. The downside is that if KeyError is raised with an explanatory
string, that string will be displayed in quotes. Too bad.
If args is anything else, use the default BaseException__str__().
*/
if (PyTuple_GET_SIZE(self->args) == 1) {
return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0));
}
return BaseException_str(self);
}
ComplexExtendsException(PyExc_LookupError, KeyError, BaseException,
0, 0, 0, KeyError_str, "Mapping key not found.");
/*
* ValueError extends StandardError
*/
SimpleExtendsException(PyExc_StandardError, ValueError,
"Inappropriate argument value (of correct type).");
/*
* UnicodeError extends ValueError
*/
SimpleExtendsException(PyExc_ValueError, UnicodeError,
"Unicode related error.");
#ifdef Py_USING_UNICODE
static int
get_int(PyObject *attr, Py_ssize_t *value, const char *name)
{
if (!attr) {
PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
return -1;
}
if (PyInt_Check(attr)) {
*value = PyInt_AS_LONG(attr);
} else if (PyLong_Check(attr)) {
*value = _PyLong_AsSsize_t(attr);
if (*value == -1 && PyErr_Occurred())
return -1;
} else {
PyErr_Format(PyExc_TypeError, "%.200s attribute must be int", name);
return -1;
}
return 0;
}
static int
set_ssize_t(PyObject **attr, Py_ssize_t value)
{
PyObject *obj = PyInt_FromSsize_t(value);
if (!obj)
return -1;
Py_CLEAR(*attr);
*attr = obj;
return 0;
}
static PyObject *
get_string(PyObject *attr, const char *name)
{
if (!attr) {
PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
return NULL;
}
if (!PyString_Check(attr)) {
PyErr_Format(PyExc_TypeError, "%.200s attribute must be str", name);
return NULL;
}
Py_INCREF(attr);
return attr;
}
static int
set_string(PyObject **attr, const char *value)
{
PyObject *obj = PyString_FromString(value);
if (!obj)
return -1;
Py_CLEAR(*attr);
*attr = obj;
return 0;
}
static PyObject *
get_unicode(PyObject *attr, const char *name)
{
if (!attr) {
PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
return NULL;
}
if (!PyUnicode_Check(attr)) {
PyErr_Format(PyExc_TypeError,
"%.200s attribute must be unicode", name);
return NULL;
}
Py_INCREF(attr);
return attr;
}
PyObject *
PyUnicodeEncodeError_GetEncoding(PyObject *exc)
{
return get_string(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
}
PyObject *
PyUnicodeDecodeError_GetEncoding(PyObject *exc)
{
return get_string(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
}
PyObject *
PyUnicodeEncodeError_GetObject(PyObject *exc)
{
return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
}
PyObject *
PyUnicodeDecodeError_GetObject(PyObject *exc)
{
return get_string(((PyUnicodeErrorObject *)exc)->object, "object");
}
PyObject *
PyUnicodeTranslateError_GetObject(PyObject *exc)
{
return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
}
int
PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
{
if (!get_int(((PyUnicodeErrorObject *)exc)->start, start, "start")) {
Py_ssize_t size;
PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
"object");
if (!obj) return -1;
size = PyUnicode_GET_SIZE(obj);
if (*start<0)
*start = 0; /*XXX check for values <0*/
if (*start>=size)
*start = size-1;
Py_DECREF(obj);
return 0;
}
return -1;
}
int
PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
{
if (!get_int(((PyUnicodeErrorObject *)exc)->start, start, "start")) {
Py_ssize_t size;
PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object,
"object");
if (!obj) return -1;
size = PyString_GET_SIZE(obj);
if (*start<0)
*start = 0;
if (*start>=size)
*start = size-1;
Py_DECREF(obj);
return 0;
}
return -1;
}
int
PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
{
return PyUnicodeEncodeError_GetStart(exc, start);
}
int
PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
{
return set_ssize_t(&((PyUnicodeErrorObject *)exc)->start, start);
}
int
PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
{
return set_ssize_t(&((PyUnicodeErrorObject *)exc)->start, start);
}
int
PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
{
return set_ssize_t(&((PyUnicodeErrorObject *)exc)->start, start);
}
int
PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
{
if (!get_int(((PyUnicodeErrorObject *)exc)->end, end, "end")) {
Py_ssize_t size;
PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
"object");
if (!obj) return -1;
size = PyUnicode_GET_SIZE(obj);
if (*end<1)
*end = 1;
if (*end>size)
*end = size;
Py_DECREF(obj);
return 0;
}
return -1;
}
int
PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
{
if (!get_int(((PyUnicodeErrorObject *)exc)->end, end, "end")) {
Py_ssize_t size;
PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object,
"object");
if (!obj) return -1;
size = PyString_GET_SIZE(obj);
if (*end<1)
*end = 1;
if (*end>size)
*end = size;
Py_DECREF(obj);
return 0;
}
return -1;
}
int
PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *start)
{
return PyUnicodeEncodeError_GetEnd(exc, start);
}
int
PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
{
return set_ssize_t(&((PyUnicodeErrorObject *)exc)->end, end);
}
int
PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
{
return set_ssize_t(&((PyUnicodeErrorObject *)exc)->end, end);
}
int
PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
{
return set_ssize_t(&((PyUnicodeErrorObject *)exc)->end, end);
}
PyObject *
PyUnicodeEncodeError_GetReason(PyObject *exc)
{
return get_string(((PyUnicodeErrorObject *)exc)->reason, "reason");
}
PyObject *
PyUnicodeDecodeError_GetReason(PyObject *exc)
{
return get_string(((PyUnicodeErrorObject *)exc)->reason, "reason");
}
PyObject *
PyUnicodeTranslateError_GetReason(PyObject *exc)
{
return get_string(((PyUnicodeErrorObject *)exc)->reason, "reason");
}
int
PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
{
return set_string(&((PyUnicodeErrorObject *)exc)->reason, reason);
}
int
PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
{
return set_string(&((PyUnicodeErrorObject *)exc)->reason, reason);
}
int
PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
{
return set_string(&((PyUnicodeErrorObject *)exc)->reason, reason);
}
static int
UnicodeError_init(PyUnicodeErrorObject *self, PyObject *args, PyObject *kwds,
PyTypeObject *objecttype)
{
Py_CLEAR(self->encoding);
Py_CLEAR(self->object);
Py_CLEAR(self->start);
Py_CLEAR(self->end);
Py_CLEAR(self->reason);
if (!PyArg_ParseTuple(args, "O!O!O!O!O!",
&PyString_Type, &self->encoding,
objecttype, &self->object,
&PyInt_Type, &self->start,
&PyInt_Type, &self->end,
&PyString_Type, &self->reason)) {
self->encoding = self->object = self->start = self->end =
self->reason = NULL;
return -1;
}
Py_INCREF(self->encoding);
Py_INCREF(self->object);
Py_INCREF(self->start);
Py_INCREF(self->end);
Py_INCREF(self->reason);
return 0;
}
static int
UnicodeError_clear(PyUnicodeErrorObject *self)
{
Py_CLEAR(self->encoding);
Py_CLEAR(self->object);
Py_CLEAR(self->start);
Py_CLEAR(self->end);
Py_CLEAR(self->reason);
return BaseException_clear((PyBaseExceptionObject *)self);
}
static void
UnicodeError_dealloc(PyUnicodeErrorObject *self)
{
UnicodeError_clear(self);
self->ob_type->tp_free((PyObject *)self);
}
static int
UnicodeError_traverse(PyUnicodeErrorObject *self, visitproc visit, void *arg)
{
Py_VISIT(self->encoding);
Py_VISIT(self->object);
Py_VISIT(self->start);
Py_VISIT(self->end);
Py_VISIT(self->reason);
return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
}
static PyMemberDef UnicodeError_members[] = {
{"message", T_OBJECT, offsetof(PyUnicodeErrorObject, message), 0,
PyDoc_STR("exception message")},
{"encoding", T_OBJECT, offsetof(PyUnicodeErrorObject, encoding), 0,
PyDoc_STR("exception encoding")},
{"object", T_OBJECT, offsetof(PyUnicodeErrorObject, object), 0,
PyDoc_STR("exception object")},
{"start", T_OBJECT, offsetof(PyUnicodeErrorObject, start), 0,
PyDoc_STR("exception start")},
{"end", T_OBJECT, offsetof(PyUnicodeErrorObject, end), 0,
PyDoc_STR("exception end")},
{"reason", T_OBJECT, offsetof(PyUnicodeErrorObject, reason), 0,
PyDoc_STR("exception reason")},
{NULL} /* Sentinel */
};
/*
* UnicodeEncodeError extends UnicodeError
*/
static int
UnicodeEncodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
{
if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
return -1;
return UnicodeError_init((PyUnicodeErrorObject *)self, args,
kwds, &PyUnicode_Type);
}
static PyObject *
UnicodeEncodeError_str(PyObject *self)
{
Py_ssize_t start;
Py_ssize_t end;
if (PyUnicodeEncodeError_GetStart(self, &start))
return NULL;
if (PyUnicodeEncodeError_GetEnd(self, &end))
return NULL;
if (end==start+1) {
int badchar = (int)PyUnicode_AS_UNICODE(((PyUnicodeErrorObject *)self)->object)[start];
char badchar_str[20];
if (badchar <= 0xff)
PyOS_snprintf(badchar_str, sizeof(badchar_str), "x%02x", badchar);
else if (badchar <= 0xffff)
PyOS_snprintf(badchar_str, sizeof(badchar_str), "u%04x", badchar);
else
PyOS_snprintf(badchar_str, sizeof(badchar_str), "U%08x", badchar);
return PyString_FromFormat(
"'%.400s' codec can't encode character u'\\%s' in position %zd: %.400s",
PyString_AS_STRING(((PyUnicodeErrorObject *)self)->encoding),
badchar_str,
start,
PyString_AS_STRING(((PyUnicodeErrorObject *)self)->reason)
);
}
return PyString_FromFormat(
"'%.400s' codec can't encode characters in position %zd-%zd: %.400s",
PyString_AS_STRING(((PyUnicodeErrorObject *)self)->encoding),
start,
(end-1),
PyString_AS_STRING(((PyUnicodeErrorObject *)self)->reason)
);
}
static PyTypeObject _PyExc_UnicodeEncodeError = {
PyObject_HEAD_INIT(NULL)
0,
"UnicodeEncodeError",
sizeof(PyUnicodeErrorObject), 0,
(destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
(reprfunc)UnicodeEncodeError_str, 0, 0, 0,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
PyDoc_STR("Unicode encoding error."), (traverseproc)UnicodeError_traverse,
(inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
(initproc)UnicodeEncodeError_init, 0, BaseException_new,
};
PyObject *PyExc_UnicodeEncodeError = (PyObject *)&_PyExc_UnicodeEncodeError;
PyObject *
PyUnicodeEncodeError_Create(
const char *encoding, const Py_UNICODE *object, Py_ssize_t length,
Py_ssize_t start, Py_ssize_t end, const char *reason)
{
return PyObject_CallFunction(PyExc_UnicodeEncodeError, "su#nns",
encoding, object, length, start, end, reason);
}
/*
* UnicodeDecodeError extends UnicodeError
*/
static int
UnicodeDecodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
{
if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
return -1;
return UnicodeError_init((PyUnicodeErrorObject *)self, args,
kwds, &PyString_Type);
}
static PyObject *
UnicodeDecodeError_str(PyObject *self)
{
Py_ssize_t start = 0;
Py_ssize_t end = 0;
if (PyUnicodeDecodeError_GetStart(self, &start))
return NULL;
if (PyUnicodeDecodeError_GetEnd(self, &end))
return NULL;
if (end==start+1) {
/* FromFormat does not support %02x, so format that separately */
char byte[4];
PyOS_snprintf(byte, sizeof(byte), "%02x",
((int)PyString_AS_STRING(((PyUnicodeErrorObject *)self)->object)[start])&0xff);
return PyString_FromFormat(
"'%.400s' codec can't decode byte 0x%s in position %zd: %.400s",
PyString_AS_STRING(((PyUnicodeErrorObject *)self)->encoding),
byte,
start,
PyString_AS_STRING(((PyUnicodeErrorObject *)self)->reason)
);
}
return PyString_FromFormat(
"'%.400s' codec can't decode bytes in position %zd-%zd: %.400s",
PyString_AS_STRING(((PyUnicodeErrorObject *)self)->encoding),
start,
(end-1),
PyString_AS_STRING(((PyUnicodeErrorObject *)self)->reason)
);
}
static PyTypeObject _PyExc_UnicodeDecodeError = {
PyObject_HEAD_INIT(NULL)
0,
EXC_MODULE_NAME "UnicodeDecodeError",
sizeof(PyUnicodeErrorObject), 0,
(destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
(reprfunc)UnicodeDecodeError_str, 0, 0, 0,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
PyDoc_STR("Unicode decoding error."), (traverseproc)UnicodeError_traverse,
(inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
(initproc)UnicodeDecodeError_init, 0, BaseException_new,
};
PyObject *PyExc_UnicodeDecodeError = (PyObject *)&_PyExc_UnicodeDecodeError;
PyObject *
PyUnicodeDecodeError_Create(
const char *encoding, const char *object, Py_ssize_t length,
Py_ssize_t start, Py_ssize_t end, const char *reason)
{
assert(length < INT_MAX);
assert(start < INT_MAX);
assert(end < INT_MAX);
return PyObject_CallFunction(PyExc_UnicodeDecodeError, "ss#nns",
encoding, object, length, start, end, reason);
}
/*
* UnicodeTranslateError extends UnicodeError
*/
static int
UnicodeTranslateError_init(PyUnicodeErrorObject *self, PyObject *args,
PyObject *kwds)
{
if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
return -1;
Py_CLEAR(self->object);
Py_CLEAR(self->start);
Py_CLEAR(self->end);
Py_CLEAR(self->reason);
if (!PyArg_ParseTuple(args, "O!O!O!O!",
&PyUnicode_Type, &self->object,
&PyInt_Type, &self->start,
&PyInt_Type, &self->end,
&PyString_Type, &self->reason)) {
self->object = self->start = self->end = self->reason = NULL;
return -1;
}
Py_INCREF(self->object);
Py_INCREF(self->start);
Py_INCREF(self->end);
Py_INCREF(self->reason);
return 0;
}
static PyObject *
UnicodeTranslateError_str(PyObject *self)
{
Py_ssize_t start;
Py_ssize_t end;
if (PyUnicodeTranslateError_GetStart(self, &start))
return NULL;
if (PyUnicodeTranslateError_GetEnd(self, &end))
return NULL;
if (end==start+1) {
int badchar = (int)PyUnicode_AS_UNICODE(((PyUnicodeErrorObject *)self)->object)[start];
char badchar_str[20];
if (badchar <= 0xff)
PyOS_snprintf(badchar_str, sizeof(badchar_str), "x%02x", badchar);
else if (badchar <= 0xffff)
PyOS_snprintf(badchar_str, sizeof(badchar_str), "u%04x", badchar);
else
PyOS_snprintf(badchar_str, sizeof(badchar_str), "U%08x", badchar);
return PyString_FromFormat(
"can't translate character u'\\%s' in position %zd: %.400s",
badchar_str,
start,
PyString_AS_STRING(((PyUnicodeErrorObject *)self)->reason)
);
}
return PyString_FromFormat(
"can't translate characters in position %zd-%zd: %.400s",
start,
(end-1),
PyString_AS_STRING(((PyUnicodeErrorObject *)self)->reason)
);
}
static PyTypeObject _PyExc_UnicodeTranslateError = {
PyObject_HEAD_INIT(NULL)
0,
EXC_MODULE_NAME "UnicodeTranslateError",
sizeof(PyUnicodeErrorObject), 0,
(destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
(reprfunc)UnicodeTranslateError_str, 0, 0, 0,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
PyDoc_STR("Unicode decoding error."), (traverseproc)UnicodeError_traverse,
(inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
(initproc)UnicodeTranslateError_init, 0, BaseException_new,
};
PyObject *PyExc_UnicodeTranslateError = (PyObject *)&_PyExc_UnicodeTranslateError;
PyObject *
PyUnicodeTranslateError_Create(
const Py_UNICODE *object, Py_ssize_t length,
Py_ssize_t start, Py_ssize_t end, const char *reason)
{
return PyObject_CallFunction(PyExc_UnicodeTranslateError, "u#nns",
object, length, start, end, reason);
}
#endif
/*
* AssertionError extends StandardError
*/
SimpleExtendsException(PyExc_StandardError, AssertionError,
"Assertion failed.");
/*
* ArithmeticError extends StandardError
*/
SimpleExtendsException(PyExc_StandardError, ArithmeticError,
"Base class for arithmetic errors.");
/*
* FloatingPointError extends ArithmeticError
*/
SimpleExtendsException(PyExc_ArithmeticError, FloatingPointError,
"Floating point operation failed.");
/*
* OverflowError extends ArithmeticError
*/
SimpleExtendsException(PyExc_ArithmeticError, OverflowError,
"Result too large to be represented.");
/*
* ZeroDivisionError extends ArithmeticError
*/
SimpleExtendsException(PyExc_ArithmeticError, ZeroDivisionError,
"Second argument to a division or modulo operation was zero.");
/*
* SystemError extends StandardError
*/
SimpleExtendsException(PyExc_StandardError, SystemError,
"Internal error in the Python interpreter.\n"
"\n"
"Please report this to the Python maintainer, along with the traceback,\n"
"the Python version, and the hardware/OS platform and version.");
/*
* ReferenceError extends StandardError
*/
SimpleExtendsException(PyExc_StandardError, ReferenceError,
"Weak ref proxy used after referent went away.");
/*
* MemoryError extends StandardError
*/
SimpleExtendsException(PyExc_StandardError, MemoryError, "Out of memory.");
/* Warning category docstrings */
/*
* Warning extends Exception
*/
SimpleExtendsException(PyExc_Exception, Warning,
"Base class for warning categories.");
/*
* UserWarning extends Warning
*/
SimpleExtendsException(PyExc_Warning, UserWarning,
"Base class for warnings generated by user code.");
/*
* DeprecationWarning extends Warning
*/
SimpleExtendsException(PyExc_Warning, DeprecationWarning,
"Base class for warnings about deprecated features.");
/*
* PendingDeprecationWarning extends Warning
*/
SimpleExtendsException(PyExc_Warning, PendingDeprecationWarning,
"Base class for warnings about features which will be deprecated\n"
"in the future.");
/*
* SyntaxWarning extends Warning
*/
SimpleExtendsException(PyExc_Warning, SyntaxWarning,
"Base class for warnings about dubious syntax.");
/*
* RuntimeWarning extends Warning
*/
SimpleExtendsException(PyExc_Warning, RuntimeWarning,
"Base class for warnings about dubious runtime behavior.");
/*
* FutureWarning extends Warning
*/
SimpleExtendsException(PyExc_Warning, FutureWarning,
"Base class for warnings about constructs that will change semantically\n"
"in the future.");
/*
* ImportWarning extends Warning
*/
SimpleExtendsException(PyExc_Warning, ImportWarning,
"Base class for warnings about probable mistakes in module imports");
/*
* UnicodeWarning extends Warning
*/
SimpleExtendsException(PyExc_Warning, UnicodeWarning,
"Base class for warnings about Unicode related problems, mostly\n"
"related to conversion problems.");
/* Pre-computed MemoryError instance. Best to create this as early as
* possible and not wait until a MemoryError is actually raised!
*/
PyObject *PyExc_MemoryErrorInst=NULL;
/* module global functions */
static PyMethodDef functions[] = {
/* Sentinel */
{NULL, NULL}
};
#define PRE_INIT(TYPE) if (PyType_Ready(&_PyExc_ ## TYPE) < 0) \
Py_FatalError("exceptions bootstrapping error.");
#define POST_INIT(TYPE) Py_INCREF(PyExc_ ## TYPE); \
PyModule_AddObject(m, # TYPE, PyExc_ ## TYPE); \
if (PyDict_SetItemString(bdict, # TYPE, PyExc_ ## TYPE)) \
Py_FatalError("Module dictionary insertion problem.");
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
/* crt variable checking in VisualStudio .NET 2005 */
#include <crtdbg.h>
static int prevCrtReportMode;
static _invalid_parameter_handler prevCrtHandler;
/* Invalid parameter handler. Sets a ValueError exception */
static void
InvalidParameterHandler(
const wchar_t * expression,
const wchar_t * function,
const wchar_t * file,
unsigned int line,
uintptr_t pReserved)
{
/* Do nothing, allow execution to continue. Usually this
* means that the CRT will set errno to EINVAL
*/
}
#endif
PyMODINIT_FUNC
_PyExc_Init(void)
{
PyObject *m, *bltinmod, *bdict;
PRE_INIT(BaseException)
PRE_INIT(Exception)
PRE_INIT(StandardError)
PRE_INIT(TypeError)
PRE_INIT(StopIteration)
PRE_INIT(GeneratorExit)
PRE_INIT(SystemExit)
PRE_INIT(KeyboardInterrupt)
PRE_INIT(ImportError)
PRE_INIT(EnvironmentError)
PRE_INIT(IOError)
PRE_INIT(OSError)
#ifdef MS_WINDOWS
PRE_INIT(WindowsError)
#endif
#ifdef __VMS
PRE_INIT(VMSError)
#endif
PRE_INIT(EOFError)
PRE_INIT(RuntimeError)
PRE_INIT(NotImplementedError)
PRE_INIT(NameError)
PRE_INIT(UnboundLocalError)
PRE_INIT(AttributeError)
PRE_INIT(SyntaxError)
PRE_INIT(IndentationError)
PRE_INIT(TabError)
PRE_INIT(LookupError)
PRE_INIT(IndexError)
PRE_INIT(KeyError)
PRE_INIT(ValueError)
PRE_INIT(UnicodeError)
#ifdef Py_USING_UNICODE
PRE_INIT(UnicodeEncodeError)
PRE_INIT(UnicodeDecodeError)
PRE_INIT(UnicodeTranslateError)
#endif
PRE_INIT(AssertionError)
PRE_INIT(ArithmeticError)
PRE_INIT(FloatingPointError)
PRE_INIT(OverflowError)
PRE_INIT(ZeroDivisionError)
PRE_INIT(SystemError)
PRE_INIT(ReferenceError)
PRE_INIT(MemoryError)
PRE_INIT(Warning)
PRE_INIT(UserWarning)
PRE_INIT(DeprecationWarning)
PRE_INIT(PendingDeprecationWarning)
PRE_INIT(SyntaxWarning)
PRE_INIT(RuntimeWarning)
PRE_INIT(FutureWarning)
PRE_INIT(ImportWarning)
PRE_INIT(UnicodeWarning)
m = Py_InitModule4("exceptions", functions, exceptions_doc,
(PyObject *)NULL, PYTHON_API_VERSION);
if (m == NULL) return;
bltinmod = PyImport_ImportModule("__builtin__");
if (bltinmod == NULL)
Py_FatalError("exceptions bootstrapping error.");
bdict = PyModule_GetDict(bltinmod);
if (bdict == NULL)
Py_FatalError("exceptions bootstrapping error.");
POST_INIT(BaseException)
POST_INIT(Exception)
POST_INIT(StandardError)
POST_INIT(TypeError)
POST_INIT(StopIteration)
POST_INIT(GeneratorExit)
POST_INIT(SystemExit)
POST_INIT(KeyboardInterrupt)
POST_INIT(ImportError)
POST_INIT(EnvironmentError)
POST_INIT(IOError)
POST_INIT(OSError)
#ifdef MS_WINDOWS
POST_INIT(WindowsError)
#endif
#ifdef __VMS
POST_INIT(VMSError)
#endif
POST_INIT(EOFError)
POST_INIT(RuntimeError)
POST_INIT(NotImplementedError)
POST_INIT(NameError)
POST_INIT(UnboundLocalError)
POST_INIT(AttributeError)
POST_INIT(SyntaxError)
POST_INIT(IndentationError)
POST_INIT(TabError)
POST_INIT(LookupError)
POST_INIT(IndexError)
POST_INIT(KeyError)
POST_INIT(ValueError)
POST_INIT(UnicodeError)
#ifdef Py_USING_UNICODE
POST_INIT(UnicodeEncodeError)
POST_INIT(UnicodeDecodeError)
POST_INIT(UnicodeTranslateError)
#endif
POST_INIT(AssertionError)
POST_INIT(ArithmeticError)
POST_INIT(FloatingPointError)
POST_INIT(OverflowError)
POST_INIT(ZeroDivisionError)
POST_INIT(SystemError)
POST_INIT(ReferenceError)
POST_INIT(MemoryError)
POST_INIT(Warning)
POST_INIT(UserWarning)
POST_INIT(DeprecationWarning)
POST_INIT(PendingDeprecationWarning)
POST_INIT(SyntaxWarning)
POST_INIT(RuntimeWarning)
POST_INIT(FutureWarning)
POST_INIT(ImportWarning)
POST_INIT(UnicodeWarning)
PyExc_MemoryErrorInst = BaseException_new(&_PyExc_MemoryError, NULL, NULL);
if (!PyExc_MemoryErrorInst)
Py_FatalError("Cannot pre-allocate MemoryError instance\n");
Py_DECREF(bltinmod);
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
/* Set CRT argument error handler */
prevCrtHandler = _set_invalid_parameter_handler(InvalidParameterHandler);
/* turn off assertions in debug mode */
prevCrtReportMode = _CrtSetReportMode(_CRT_ASSERT, 0);
#endif
}
void
_PyExc_Fini(void)
{
Py_XDECREF(PyExc_MemoryErrorInst);
PyExc_MemoryErrorInst = NULL;
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
/* reset CRT error handling */
_set_invalid_parameter_handler(prevCrtHandler);
_CrtSetReportMode(_CRT_ASSERT, prevCrtReportMode);
#endif
}