exceptions.c 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841
  1. /*
  2. * New exceptions.c written in Iceland by Richard Jones and Georg Brandl.
  3. *
  4. * Thanks go to Tim Peters and Michael Hudson for debugging.
  5. */
  6. #define PY_SSIZE_T_CLEAN
  7. #include <Python.h>
  8. #include <stdbool.h>
  9. #include "pycore_ceval.h" // _Py_EnterRecursiveCall
  10. #include "pycore_pyerrors.h" // struct _PyErr_SetRaisedException
  11. #include "pycore_exceptions.h" // struct _Py_exc_state
  12. #include "pycore_initconfig.h"
  13. #include "pycore_object.h"
  14. #include "structmember.h" // PyMemberDef
  15. #include "osdefs.h" // SEP
  16. /* Compatibility aliases */
  17. PyObject *PyExc_EnvironmentError = NULL; // borrowed ref
  18. PyObject *PyExc_IOError = NULL; // borrowed ref
  19. #ifdef MS_WINDOWS
  20. PyObject *PyExc_WindowsError = NULL; // borrowed ref
  21. #endif
  22. static struct _Py_exc_state*
  23. get_exc_state(void)
  24. {
  25. PyInterpreterState *interp = _PyInterpreterState_GET();
  26. return &interp->exc_state;
  27. }
  28. /* NOTE: If the exception class hierarchy changes, don't forget to update
  29. * Lib/test/exception_hierarchy.txt
  30. */
  31. /*
  32. * BaseException
  33. */
  34. static PyObject *
  35. BaseException_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  36. {
  37. PyBaseExceptionObject *self;
  38. self = (PyBaseExceptionObject *)type->tp_alloc(type, 0);
  39. if (!self)
  40. return NULL;
  41. /* the dict is created on the fly in PyObject_GenericSetAttr */
  42. self->dict = NULL;
  43. self->notes = NULL;
  44. self->traceback = self->cause = self->context = NULL;
  45. self->suppress_context = 0;
  46. if (args) {
  47. self->args = Py_NewRef(args);
  48. return (PyObject *)self;
  49. }
  50. self->args = PyTuple_New(0);
  51. if (!self->args) {
  52. Py_DECREF(self);
  53. return NULL;
  54. }
  55. return (PyObject *)self;
  56. }
  57. static int
  58. BaseException_init(PyBaseExceptionObject *self, PyObject *args, PyObject *kwds)
  59. {
  60. if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
  61. return -1;
  62. Py_XSETREF(self->args, Py_NewRef(args));
  63. return 0;
  64. }
  65. static int
  66. BaseException_clear(PyBaseExceptionObject *self)
  67. {
  68. Py_CLEAR(self->dict);
  69. Py_CLEAR(self->args);
  70. Py_CLEAR(self->notes);
  71. Py_CLEAR(self->traceback);
  72. Py_CLEAR(self->cause);
  73. Py_CLEAR(self->context);
  74. return 0;
  75. }
  76. static void
  77. BaseException_dealloc(PyBaseExceptionObject *self)
  78. {
  79. PyObject_GC_UnTrack(self);
  80. // bpo-44348: The trashcan mechanism prevents stack overflow when deleting
  81. // long chains of exceptions. For example, exceptions can be chained
  82. // through the __context__ attributes or the __traceback__ attribute.
  83. Py_TRASHCAN_BEGIN(self, BaseException_dealloc)
  84. BaseException_clear(self);
  85. Py_TYPE(self)->tp_free((PyObject *)self);
  86. Py_TRASHCAN_END
  87. }
  88. static int
  89. BaseException_traverse(PyBaseExceptionObject *self, visitproc visit, void *arg)
  90. {
  91. Py_VISIT(self->dict);
  92. Py_VISIT(self->args);
  93. Py_VISIT(self->notes);
  94. Py_VISIT(self->traceback);
  95. Py_VISIT(self->cause);
  96. Py_VISIT(self->context);
  97. return 0;
  98. }
  99. static PyObject *
  100. BaseException_str(PyBaseExceptionObject *self)
  101. {
  102. switch (PyTuple_GET_SIZE(self->args)) {
  103. case 0:
  104. return PyUnicode_FromString("");
  105. case 1:
  106. return PyObject_Str(PyTuple_GET_ITEM(self->args, 0));
  107. default:
  108. return PyObject_Str(self->args);
  109. }
  110. }
  111. static PyObject *
  112. BaseException_repr(PyBaseExceptionObject *self)
  113. {
  114. const char *name = _PyType_Name(Py_TYPE(self));
  115. if (PyTuple_GET_SIZE(self->args) == 1)
  116. return PyUnicode_FromFormat("%s(%R)", name,
  117. PyTuple_GET_ITEM(self->args, 0));
  118. else
  119. return PyUnicode_FromFormat("%s%R", name, self->args);
  120. }
  121. /* Pickling support */
  122. static PyObject *
  123. BaseException_reduce(PyBaseExceptionObject *self, PyObject *Py_UNUSED(ignored))
  124. {
  125. if (self->args && self->dict)
  126. return PyTuple_Pack(3, Py_TYPE(self), self->args, self->dict);
  127. else
  128. return PyTuple_Pack(2, Py_TYPE(self), self->args);
  129. }
  130. /*
  131. * Needed for backward compatibility, since exceptions used to store
  132. * all their attributes in the __dict__. Code is taken from cPickle's
  133. * load_build function.
  134. */
  135. static PyObject *
  136. BaseException_setstate(PyObject *self, PyObject *state)
  137. {
  138. PyObject *d_key, *d_value;
  139. Py_ssize_t i = 0;
  140. if (state != Py_None) {
  141. if (!PyDict_Check(state)) {
  142. PyErr_SetString(PyExc_TypeError, "state is not a dictionary");
  143. return NULL;
  144. }
  145. while (PyDict_Next(state, &i, &d_key, &d_value)) {
  146. Py_INCREF(d_key);
  147. Py_INCREF(d_value);
  148. int res = PyObject_SetAttr(self, d_key, d_value);
  149. Py_DECREF(d_value);
  150. Py_DECREF(d_key);
  151. if (res < 0) {
  152. return NULL;
  153. }
  154. }
  155. }
  156. Py_RETURN_NONE;
  157. }
  158. static PyObject *
  159. BaseException_with_traceback(PyObject *self, PyObject *tb) {
  160. if (PyException_SetTraceback(self, tb))
  161. return NULL;
  162. return Py_NewRef(self);
  163. }
  164. PyDoc_STRVAR(with_traceback_doc,
  165. "Exception.with_traceback(tb) --\n\
  166. set self.__traceback__ to tb and return self.");
  167. static inline PyBaseExceptionObject*
  168. _PyBaseExceptionObject_cast(PyObject *exc)
  169. {
  170. assert(PyExceptionInstance_Check(exc));
  171. return (PyBaseExceptionObject *)exc;
  172. }
  173. static PyObject *
  174. BaseException_add_note(PyObject *self, PyObject *note)
  175. {
  176. if (!PyUnicode_Check(note)) {
  177. PyErr_Format(PyExc_TypeError,
  178. "note must be a str, not '%s'",
  179. Py_TYPE(note)->tp_name);
  180. return NULL;
  181. }
  182. PyObject *notes;
  183. if (_PyObject_LookupAttr(self, &_Py_ID(__notes__), &notes) < 0) {
  184. return NULL;
  185. }
  186. if (notes == NULL) {
  187. notes = PyList_New(0);
  188. if (notes == NULL) {
  189. return NULL;
  190. }
  191. if (PyObject_SetAttr(self, &_Py_ID(__notes__), notes) < 0) {
  192. Py_DECREF(notes);
  193. return NULL;
  194. }
  195. }
  196. else if (!PyList_Check(notes)) {
  197. Py_DECREF(notes);
  198. PyErr_SetString(PyExc_TypeError, "Cannot add note: __notes__ is not a list");
  199. return NULL;
  200. }
  201. if (PyList_Append(notes, note) < 0) {
  202. Py_DECREF(notes);
  203. return NULL;
  204. }
  205. Py_DECREF(notes);
  206. Py_RETURN_NONE;
  207. }
  208. PyDoc_STRVAR(add_note_doc,
  209. "Exception.add_note(note) --\n\
  210. add a note to the exception");
  211. static PyMethodDef BaseException_methods[] = {
  212. {"__reduce__", (PyCFunction)BaseException_reduce, METH_NOARGS },
  213. {"__setstate__", (PyCFunction)BaseException_setstate, METH_O },
  214. {"with_traceback", (PyCFunction)BaseException_with_traceback, METH_O,
  215. with_traceback_doc},
  216. {"add_note", (PyCFunction)BaseException_add_note, METH_O,
  217. add_note_doc},
  218. {NULL, NULL, 0, NULL},
  219. };
  220. static PyObject *
  221. BaseException_get_args(PyBaseExceptionObject *self, void *Py_UNUSED(ignored))
  222. {
  223. if (self->args == NULL) {
  224. Py_RETURN_NONE;
  225. }
  226. return Py_NewRef(self->args);
  227. }
  228. static int
  229. BaseException_set_args(PyBaseExceptionObject *self, PyObject *val, void *Py_UNUSED(ignored))
  230. {
  231. PyObject *seq;
  232. if (val == NULL) {
  233. PyErr_SetString(PyExc_TypeError, "args may not be deleted");
  234. return -1;
  235. }
  236. seq = PySequence_Tuple(val);
  237. if (!seq)
  238. return -1;
  239. Py_XSETREF(self->args, seq);
  240. return 0;
  241. }
  242. static PyObject *
  243. BaseException_get_tb(PyBaseExceptionObject *self, void *Py_UNUSED(ignored))
  244. {
  245. if (self->traceback == NULL) {
  246. Py_RETURN_NONE;
  247. }
  248. return Py_NewRef(self->traceback);
  249. }
  250. static int
  251. BaseException_set_tb(PyBaseExceptionObject *self, PyObject *tb, void *Py_UNUSED(ignored))
  252. {
  253. if (tb == NULL) {
  254. PyErr_SetString(PyExc_TypeError, "__traceback__ may not be deleted");
  255. return -1;
  256. }
  257. if (PyTraceBack_Check(tb)) {
  258. Py_XSETREF(self->traceback, Py_NewRef(tb));
  259. }
  260. else if (tb == Py_None) {
  261. Py_CLEAR(self->traceback);
  262. }
  263. else {
  264. PyErr_SetString(PyExc_TypeError,
  265. "__traceback__ must be a traceback or None");
  266. return -1;
  267. }
  268. return 0;
  269. }
  270. static PyObject *
  271. BaseException_get_context(PyObject *self, void *Py_UNUSED(ignored))
  272. {
  273. PyObject *res = PyException_GetContext(self);
  274. if (res)
  275. return res; /* new reference already returned above */
  276. Py_RETURN_NONE;
  277. }
  278. static int
  279. BaseException_set_context(PyObject *self, PyObject *arg, void *Py_UNUSED(ignored))
  280. {
  281. if (arg == NULL) {
  282. PyErr_SetString(PyExc_TypeError, "__context__ may not be deleted");
  283. return -1;
  284. } else if (arg == Py_None) {
  285. arg = NULL;
  286. } else if (!PyExceptionInstance_Check(arg)) {
  287. PyErr_SetString(PyExc_TypeError, "exception context must be None "
  288. "or derive from BaseException");
  289. return -1;
  290. } else {
  291. /* PyException_SetContext steals this reference */
  292. Py_INCREF(arg);
  293. }
  294. PyException_SetContext(self, arg);
  295. return 0;
  296. }
  297. static PyObject *
  298. BaseException_get_cause(PyObject *self, void *Py_UNUSED(ignored))
  299. {
  300. PyObject *res = PyException_GetCause(self);
  301. if (res)
  302. return res; /* new reference already returned above */
  303. Py_RETURN_NONE;
  304. }
  305. static int
  306. BaseException_set_cause(PyObject *self, PyObject *arg, void *Py_UNUSED(ignored))
  307. {
  308. if (arg == NULL) {
  309. PyErr_SetString(PyExc_TypeError, "__cause__ may not be deleted");
  310. return -1;
  311. } else if (arg == Py_None) {
  312. arg = NULL;
  313. } else if (!PyExceptionInstance_Check(arg)) {
  314. PyErr_SetString(PyExc_TypeError, "exception cause must be None "
  315. "or derive from BaseException");
  316. return -1;
  317. } else {
  318. /* PyException_SetCause steals this reference */
  319. Py_INCREF(arg);
  320. }
  321. PyException_SetCause(self, arg);
  322. return 0;
  323. }
  324. static PyGetSetDef BaseException_getset[] = {
  325. {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
  326. {"args", (getter)BaseException_get_args, (setter)BaseException_set_args},
  327. {"__traceback__", (getter)BaseException_get_tb, (setter)BaseException_set_tb},
  328. {"__context__", BaseException_get_context,
  329. BaseException_set_context, PyDoc_STR("exception context")},
  330. {"__cause__", BaseException_get_cause,
  331. BaseException_set_cause, PyDoc_STR("exception cause")},
  332. {NULL},
  333. };
  334. PyObject *
  335. PyException_GetTraceback(PyObject *self)
  336. {
  337. PyBaseExceptionObject *base_self = _PyBaseExceptionObject_cast(self);
  338. return Py_XNewRef(base_self->traceback);
  339. }
  340. int
  341. PyException_SetTraceback(PyObject *self, PyObject *tb)
  342. {
  343. return BaseException_set_tb(_PyBaseExceptionObject_cast(self), tb, NULL);
  344. }
  345. PyObject *
  346. PyException_GetCause(PyObject *self)
  347. {
  348. PyObject *cause = _PyBaseExceptionObject_cast(self)->cause;
  349. return Py_XNewRef(cause);
  350. }
  351. /* Steals a reference to cause */
  352. void
  353. PyException_SetCause(PyObject *self, PyObject *cause)
  354. {
  355. PyBaseExceptionObject *base_self = _PyBaseExceptionObject_cast(self);
  356. base_self->suppress_context = 1;
  357. Py_XSETREF(base_self->cause, cause);
  358. }
  359. PyObject *
  360. PyException_GetContext(PyObject *self)
  361. {
  362. PyObject *context = _PyBaseExceptionObject_cast(self)->context;
  363. return Py_XNewRef(context);
  364. }
  365. /* Steals a reference to context */
  366. void
  367. PyException_SetContext(PyObject *self, PyObject *context)
  368. {
  369. Py_XSETREF(_PyBaseExceptionObject_cast(self)->context, context);
  370. }
  371. PyObject *
  372. PyException_GetArgs(PyObject *self)
  373. {
  374. PyObject *args = _PyBaseExceptionObject_cast(self)->args;
  375. return Py_NewRef(args);
  376. }
  377. void
  378. PyException_SetArgs(PyObject *self, PyObject *args)
  379. {
  380. Py_INCREF(args);
  381. Py_XSETREF(_PyBaseExceptionObject_cast(self)->args, args);
  382. }
  383. const char *
  384. PyExceptionClass_Name(PyObject *ob)
  385. {
  386. assert(PyExceptionClass_Check(ob));
  387. return ((PyTypeObject*)ob)->tp_name;
  388. }
  389. static struct PyMemberDef BaseException_members[] = {
  390. {"__suppress_context__", T_BOOL,
  391. offsetof(PyBaseExceptionObject, suppress_context)},
  392. {NULL}
  393. };
  394. static PyTypeObject _PyExc_BaseException = {
  395. PyVarObject_HEAD_INIT(NULL, 0)
  396. "BaseException", /*tp_name*/
  397. sizeof(PyBaseExceptionObject), /*tp_basicsize*/
  398. 0, /*tp_itemsize*/
  399. (destructor)BaseException_dealloc, /*tp_dealloc*/
  400. 0, /*tp_vectorcall_offset*/
  401. 0, /*tp_getattr*/
  402. 0, /*tp_setattr*/
  403. 0, /*tp_as_async*/
  404. (reprfunc)BaseException_repr, /*tp_repr*/
  405. 0, /*tp_as_number*/
  406. 0, /*tp_as_sequence*/
  407. 0, /*tp_as_mapping*/
  408. 0, /*tp_hash */
  409. 0, /*tp_call*/
  410. (reprfunc)BaseException_str, /*tp_str*/
  411. PyObject_GenericGetAttr, /*tp_getattro*/
  412. PyObject_GenericSetAttr, /*tp_setattro*/
  413. 0, /*tp_as_buffer*/
  414. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
  415. Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/
  416. PyDoc_STR("Common base class for all exceptions"), /* tp_doc */
  417. (traverseproc)BaseException_traverse, /* tp_traverse */
  418. (inquiry)BaseException_clear, /* tp_clear */
  419. 0, /* tp_richcompare */
  420. 0, /* tp_weaklistoffset */
  421. 0, /* tp_iter */
  422. 0, /* tp_iternext */
  423. BaseException_methods, /* tp_methods */
  424. BaseException_members, /* tp_members */
  425. BaseException_getset, /* tp_getset */
  426. 0, /* tp_base */
  427. 0, /* tp_dict */
  428. 0, /* tp_descr_get */
  429. 0, /* tp_descr_set */
  430. offsetof(PyBaseExceptionObject, dict), /* tp_dictoffset */
  431. (initproc)BaseException_init, /* tp_init */
  432. 0, /* tp_alloc */
  433. BaseException_new, /* tp_new */
  434. };
  435. /* the CPython API expects exceptions to be (PyObject *) - both a hold-over
  436. from the previous implementation and also allowing Python objects to be used
  437. in the API */
  438. PyObject *PyExc_BaseException = (PyObject *)&_PyExc_BaseException;
  439. /* note these macros omit the last semicolon so the macro invocation may
  440. * include it and not look strange.
  441. */
  442. #define SimpleExtendsException(EXCBASE, EXCNAME, EXCDOC) \
  443. static PyTypeObject _PyExc_ ## EXCNAME = { \
  444. PyVarObject_HEAD_INIT(NULL, 0) \
  445. # EXCNAME, \
  446. sizeof(PyBaseExceptionObject), \
  447. 0, (destructor)BaseException_dealloc, 0, 0, 0, 0, 0, 0, 0, \
  448. 0, 0, 0, 0, 0, 0, 0, \
  449. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
  450. PyDoc_STR(EXCDOC), (traverseproc)BaseException_traverse, \
  451. (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
  452. 0, 0, 0, offsetof(PyBaseExceptionObject, dict), \
  453. (initproc)BaseException_init, 0, BaseException_new,\
  454. }; \
  455. PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
  456. #define MiddlingExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDOC) \
  457. static PyTypeObject _PyExc_ ## EXCNAME = { \
  458. PyVarObject_HEAD_INIT(NULL, 0) \
  459. # EXCNAME, \
  460. sizeof(Py ## EXCSTORE ## Object), \
  461. 0, (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
  462. 0, 0, 0, 0, 0, \
  463. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
  464. PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
  465. (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
  466. 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
  467. (initproc)EXCSTORE ## _init, 0, 0, \
  468. }; \
  469. PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
  470. #define ComplexExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCNEW, \
  471. EXCMETHODS, EXCMEMBERS, EXCGETSET, \
  472. EXCSTR, EXCDOC) \
  473. static PyTypeObject _PyExc_ ## EXCNAME = { \
  474. PyVarObject_HEAD_INIT(NULL, 0) \
  475. # EXCNAME, \
  476. sizeof(Py ## EXCSTORE ## Object), 0, \
  477. (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
  478. (reprfunc)EXCSTR, 0, 0, 0, \
  479. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
  480. PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
  481. (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, EXCMETHODS, \
  482. EXCMEMBERS, EXCGETSET, &_ ## EXCBASE, \
  483. 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
  484. (initproc)EXCSTORE ## _init, 0, EXCNEW,\
  485. }; \
  486. PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
  487. /*
  488. * Exception extends BaseException
  489. */
  490. SimpleExtendsException(PyExc_BaseException, Exception,
  491. "Common base class for all non-exit exceptions.");
  492. /*
  493. * TypeError extends Exception
  494. */
  495. SimpleExtendsException(PyExc_Exception, TypeError,
  496. "Inappropriate argument type.");
  497. /*
  498. * StopAsyncIteration extends Exception
  499. */
  500. SimpleExtendsException(PyExc_Exception, StopAsyncIteration,
  501. "Signal the end from iterator.__anext__().");
  502. /*
  503. * StopIteration extends Exception
  504. */
  505. static PyMemberDef StopIteration_members[] = {
  506. {"value", T_OBJECT, offsetof(PyStopIterationObject, value), 0,
  507. PyDoc_STR("generator return value")},
  508. {NULL} /* Sentinel */
  509. };
  510. static int
  511. StopIteration_init(PyStopIterationObject *self, PyObject *args, PyObject *kwds)
  512. {
  513. Py_ssize_t size = PyTuple_GET_SIZE(args);
  514. PyObject *value;
  515. if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
  516. return -1;
  517. Py_CLEAR(self->value);
  518. if (size > 0)
  519. value = PyTuple_GET_ITEM(args, 0);
  520. else
  521. value = Py_None;
  522. self->value = Py_NewRef(value);
  523. return 0;
  524. }
  525. static int
  526. StopIteration_clear(PyStopIterationObject *self)
  527. {
  528. Py_CLEAR(self->value);
  529. return BaseException_clear((PyBaseExceptionObject *)self);
  530. }
  531. static void
  532. StopIteration_dealloc(PyStopIterationObject *self)
  533. {
  534. PyObject_GC_UnTrack(self);
  535. StopIteration_clear(self);
  536. Py_TYPE(self)->tp_free((PyObject *)self);
  537. }
  538. static int
  539. StopIteration_traverse(PyStopIterationObject *self, visitproc visit, void *arg)
  540. {
  541. Py_VISIT(self->value);
  542. return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
  543. }
  544. ComplexExtendsException(PyExc_Exception, StopIteration, StopIteration,
  545. 0, 0, StopIteration_members, 0, 0,
  546. "Signal the end from iterator.__next__().");
  547. /*
  548. * GeneratorExit extends BaseException
  549. */
  550. SimpleExtendsException(PyExc_BaseException, GeneratorExit,
  551. "Request that a generator exit.");
  552. /*
  553. * SystemExit extends BaseException
  554. */
  555. static int
  556. SystemExit_init(PySystemExitObject *self, PyObject *args, PyObject *kwds)
  557. {
  558. Py_ssize_t size = PyTuple_GET_SIZE(args);
  559. if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
  560. return -1;
  561. if (size == 0)
  562. return 0;
  563. if (size == 1) {
  564. Py_XSETREF(self->code, Py_NewRef(PyTuple_GET_ITEM(args, 0)));
  565. }
  566. else { /* size > 1 */
  567. Py_XSETREF(self->code, Py_NewRef(args));
  568. }
  569. return 0;
  570. }
  571. static int
  572. SystemExit_clear(PySystemExitObject *self)
  573. {
  574. Py_CLEAR(self->code);
  575. return BaseException_clear((PyBaseExceptionObject *)self);
  576. }
  577. static void
  578. SystemExit_dealloc(PySystemExitObject *self)
  579. {
  580. _PyObject_GC_UNTRACK(self);
  581. SystemExit_clear(self);
  582. Py_TYPE(self)->tp_free((PyObject *)self);
  583. }
  584. static int
  585. SystemExit_traverse(PySystemExitObject *self, visitproc visit, void *arg)
  586. {
  587. Py_VISIT(self->code);
  588. return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
  589. }
  590. static PyMemberDef SystemExit_members[] = {
  591. {"code", T_OBJECT, offsetof(PySystemExitObject, code), 0,
  592. PyDoc_STR("exception code")},
  593. {NULL} /* Sentinel */
  594. };
  595. ComplexExtendsException(PyExc_BaseException, SystemExit, SystemExit,
  596. 0, 0, SystemExit_members, 0, 0,
  597. "Request to exit from the interpreter.");
  598. /*
  599. * BaseExceptionGroup extends BaseException
  600. * ExceptionGroup extends BaseExceptionGroup and Exception
  601. */
  602. static inline PyBaseExceptionGroupObject*
  603. _PyBaseExceptionGroupObject_cast(PyObject *exc)
  604. {
  605. assert(_PyBaseExceptionGroup_Check(exc));
  606. return (PyBaseExceptionGroupObject *)exc;
  607. }
  608. static PyObject *
  609. BaseExceptionGroup_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  610. {
  611. struct _Py_exc_state *state = get_exc_state();
  612. PyTypeObject *PyExc_ExceptionGroup =
  613. (PyTypeObject*)state->PyExc_ExceptionGroup;
  614. PyObject *message = NULL;
  615. PyObject *exceptions = NULL;
  616. if (!PyArg_ParseTuple(args,
  617. "UO:BaseExceptionGroup.__new__",
  618. &message,
  619. &exceptions)) {
  620. return NULL;
  621. }
  622. if (!PySequence_Check(exceptions)) {
  623. PyErr_SetString(
  624. PyExc_TypeError,
  625. "second argument (exceptions) must be a sequence");
  626. return NULL;
  627. }
  628. exceptions = PySequence_Tuple(exceptions);
  629. if (!exceptions) {
  630. return NULL;
  631. }
  632. /* We are now holding a ref to the exceptions tuple */
  633. Py_ssize_t numexcs = PyTuple_GET_SIZE(exceptions);
  634. if (numexcs == 0) {
  635. PyErr_SetString(
  636. PyExc_ValueError,
  637. "second argument (exceptions) must be a non-empty sequence");
  638. goto error;
  639. }
  640. bool nested_base_exceptions = false;
  641. for (Py_ssize_t i = 0; i < numexcs; i++) {
  642. PyObject *exc = PyTuple_GET_ITEM(exceptions, i);
  643. if (!exc) {
  644. goto error;
  645. }
  646. if (!PyExceptionInstance_Check(exc)) {
  647. PyErr_Format(
  648. PyExc_ValueError,
  649. "Item %d of second argument (exceptions) is not an exception",
  650. i);
  651. goto error;
  652. }
  653. int is_nonbase_exception = PyObject_IsInstance(exc, PyExc_Exception);
  654. if (is_nonbase_exception < 0) {
  655. goto error;
  656. }
  657. else if (is_nonbase_exception == 0) {
  658. nested_base_exceptions = true;
  659. }
  660. }
  661. PyTypeObject *cls = type;
  662. if (cls == PyExc_ExceptionGroup) {
  663. if (nested_base_exceptions) {
  664. PyErr_SetString(PyExc_TypeError,
  665. "Cannot nest BaseExceptions in an ExceptionGroup");
  666. goto error;
  667. }
  668. }
  669. else if (cls == (PyTypeObject*)PyExc_BaseExceptionGroup) {
  670. if (!nested_base_exceptions) {
  671. /* All nested exceptions are Exception subclasses,
  672. * wrap them in an ExceptionGroup
  673. */
  674. cls = PyExc_ExceptionGroup;
  675. }
  676. }
  677. else {
  678. /* user-defined subclass */
  679. if (nested_base_exceptions) {
  680. int nonbase = PyObject_IsSubclass((PyObject*)cls, PyExc_Exception);
  681. if (nonbase == -1) {
  682. goto error;
  683. }
  684. else if (nonbase == 1) {
  685. PyErr_Format(PyExc_TypeError,
  686. "Cannot nest BaseExceptions in '%.200s'",
  687. cls->tp_name);
  688. goto error;
  689. }
  690. }
  691. }
  692. if (!cls) {
  693. /* Don't crash during interpreter shutdown
  694. * (PyExc_ExceptionGroup may have been cleared)
  695. */
  696. cls = (PyTypeObject*)PyExc_BaseExceptionGroup;
  697. }
  698. PyBaseExceptionGroupObject *self =
  699. _PyBaseExceptionGroupObject_cast(BaseException_new(cls, args, kwds));
  700. if (!self) {
  701. goto error;
  702. }
  703. self->msg = Py_NewRef(message);
  704. self->excs = exceptions;
  705. return (PyObject*)self;
  706. error:
  707. Py_DECREF(exceptions);
  708. return NULL;
  709. }
  710. PyObject *
  711. _PyExc_CreateExceptionGroup(const char *msg_str, PyObject *excs)
  712. {
  713. PyObject *msg = PyUnicode_FromString(msg_str);
  714. if (!msg) {
  715. return NULL;
  716. }
  717. PyObject *args = PyTuple_Pack(2, msg, excs);
  718. Py_DECREF(msg);
  719. if (!args) {
  720. return NULL;
  721. }
  722. PyObject *result = PyObject_CallObject(PyExc_BaseExceptionGroup, args);
  723. Py_DECREF(args);
  724. return result;
  725. }
  726. static int
  727. BaseExceptionGroup_init(PyBaseExceptionGroupObject *self,
  728. PyObject *args, PyObject *kwds)
  729. {
  730. if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds)) {
  731. return -1;
  732. }
  733. if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1) {
  734. return -1;
  735. }
  736. return 0;
  737. }
  738. static int
  739. BaseExceptionGroup_clear(PyBaseExceptionGroupObject *self)
  740. {
  741. Py_CLEAR(self->msg);
  742. Py_CLEAR(self->excs);
  743. return BaseException_clear((PyBaseExceptionObject *)self);
  744. }
  745. static void
  746. BaseExceptionGroup_dealloc(PyBaseExceptionGroupObject *self)
  747. {
  748. _PyObject_GC_UNTRACK(self);
  749. BaseExceptionGroup_clear(self);
  750. Py_TYPE(self)->tp_free((PyObject *)self);
  751. }
  752. static int
  753. BaseExceptionGroup_traverse(PyBaseExceptionGroupObject *self,
  754. visitproc visit, void *arg)
  755. {
  756. Py_VISIT(self->msg);
  757. Py_VISIT(self->excs);
  758. return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
  759. }
  760. static PyObject *
  761. BaseExceptionGroup_str(PyBaseExceptionGroupObject *self)
  762. {
  763. assert(self->msg);
  764. assert(PyUnicode_Check(self->msg));
  765. assert(PyTuple_CheckExact(self->excs));
  766. Py_ssize_t num_excs = PyTuple_Size(self->excs);
  767. return PyUnicode_FromFormat(
  768. "%S (%zd sub-exception%s)",
  769. self->msg, num_excs, num_excs > 1 ? "s" : "");
  770. }
  771. static PyObject *
  772. BaseExceptionGroup_derive(PyObject *self_, PyObject *args)
  773. {
  774. PyBaseExceptionGroupObject *self = _PyBaseExceptionGroupObject_cast(self_);
  775. PyObject *excs = NULL;
  776. if (!PyArg_ParseTuple(args, "O", &excs)) {
  777. return NULL;
  778. }
  779. PyObject *init_args = PyTuple_Pack(2, self->msg, excs);
  780. if (!init_args) {
  781. return NULL;
  782. }
  783. PyObject *eg = PyObject_CallObject(
  784. PyExc_BaseExceptionGroup, init_args);
  785. Py_DECREF(init_args);
  786. return eg;
  787. }
  788. static int
  789. exceptiongroup_subset(
  790. PyBaseExceptionGroupObject *_orig, PyObject *excs, PyObject **result)
  791. {
  792. /* Sets *result to an ExceptionGroup wrapping excs with metadata from
  793. * _orig. If excs is empty, sets *result to NULL.
  794. * Returns 0 on success and -1 on error.
  795. * This function is used by split() to construct the match/rest parts,
  796. * so excs is the matching or non-matching sub-sequence of orig->excs
  797. * (this function does not verify that it is a subsequence).
  798. */
  799. PyObject *orig = (PyObject *)_orig;
  800. *result = NULL;
  801. Py_ssize_t num_excs = PySequence_Size(excs);
  802. if (num_excs < 0) {
  803. return -1;
  804. }
  805. else if (num_excs == 0) {
  806. return 0;
  807. }
  808. PyObject *eg = PyObject_CallMethod(
  809. orig, "derive", "(O)", excs);
  810. if (!eg) {
  811. return -1;
  812. }
  813. if (!_PyBaseExceptionGroup_Check(eg)) {
  814. PyErr_SetString(PyExc_TypeError,
  815. "derive must return an instance of BaseExceptionGroup");
  816. goto error;
  817. }
  818. /* Now we hold a reference to the new eg */
  819. PyObject *tb = PyException_GetTraceback(orig);
  820. if (tb) {
  821. int res = PyException_SetTraceback(eg, tb);
  822. Py_DECREF(tb);
  823. if (res < 0) {
  824. goto error;
  825. }
  826. }
  827. PyException_SetContext(eg, PyException_GetContext(orig));
  828. PyException_SetCause(eg, PyException_GetCause(orig));
  829. PyObject *notes;
  830. if (_PyObject_LookupAttr(orig, &_Py_ID(__notes__), &notes) < 0) {
  831. goto error;
  832. }
  833. if (notes) {
  834. if (PySequence_Check(notes)) {
  835. /* Make a copy so the parts have independent notes lists. */
  836. PyObject *notes_copy = PySequence_List(notes);
  837. Py_DECREF(notes);
  838. if (notes_copy == NULL) {
  839. goto error;
  840. }
  841. int res = PyObject_SetAttr(eg, &_Py_ID(__notes__), notes_copy);
  842. Py_DECREF(notes_copy);
  843. if (res < 0) {
  844. goto error;
  845. }
  846. }
  847. else {
  848. /* __notes__ is supposed to be a list, and split() is not a
  849. * good place to report earlier user errors, so we just ignore
  850. * notes of non-sequence type.
  851. */
  852. Py_DECREF(notes);
  853. }
  854. }
  855. *result = eg;
  856. return 0;
  857. error:
  858. Py_DECREF(eg);
  859. return -1;
  860. }
  861. typedef enum {
  862. /* Exception type or tuple of thereof */
  863. EXCEPTION_GROUP_MATCH_BY_TYPE = 0,
  864. /* A PyFunction returning True for matching exceptions */
  865. EXCEPTION_GROUP_MATCH_BY_PREDICATE = 1,
  866. /* A set of the IDs of leaf exceptions to include in the result.
  867. * This matcher type is used internally by the interpreter
  868. * to construct reraised exceptions.
  869. */
  870. EXCEPTION_GROUP_MATCH_INSTANCE_IDS = 2
  871. } _exceptiongroup_split_matcher_type;
  872. static int
  873. get_matcher_type(PyObject *value,
  874. _exceptiongroup_split_matcher_type *type)
  875. {
  876. assert(value);
  877. if (PyFunction_Check(value)) {
  878. *type = EXCEPTION_GROUP_MATCH_BY_PREDICATE;
  879. return 0;
  880. }
  881. if (PyExceptionClass_Check(value)) {
  882. *type = EXCEPTION_GROUP_MATCH_BY_TYPE;
  883. return 0;
  884. }
  885. if (PyTuple_CheckExact(value)) {
  886. Py_ssize_t n = PyTuple_GET_SIZE(value);
  887. for (Py_ssize_t i=0; i<n; i++) {
  888. if (!PyExceptionClass_Check(PyTuple_GET_ITEM(value, i))) {
  889. goto error;
  890. }
  891. }
  892. *type = EXCEPTION_GROUP_MATCH_BY_TYPE;
  893. return 0;
  894. }
  895. error:
  896. PyErr_SetString(
  897. PyExc_TypeError,
  898. "expected a function, exception type or tuple of exception types");
  899. return -1;
  900. }
  901. static int
  902. exceptiongroup_split_check_match(PyObject *exc,
  903. _exceptiongroup_split_matcher_type matcher_type,
  904. PyObject *matcher_value)
  905. {
  906. switch (matcher_type) {
  907. case EXCEPTION_GROUP_MATCH_BY_TYPE: {
  908. assert(PyExceptionClass_Check(matcher_value) ||
  909. PyTuple_CheckExact(matcher_value));
  910. return PyErr_GivenExceptionMatches(exc, matcher_value);
  911. }
  912. case EXCEPTION_GROUP_MATCH_BY_PREDICATE: {
  913. assert(PyFunction_Check(matcher_value));
  914. PyObject *exc_matches = PyObject_CallOneArg(matcher_value, exc);
  915. if (exc_matches == NULL) {
  916. return -1;
  917. }
  918. int is_true = PyObject_IsTrue(exc_matches);
  919. Py_DECREF(exc_matches);
  920. return is_true;
  921. }
  922. case EXCEPTION_GROUP_MATCH_INSTANCE_IDS: {
  923. assert(PySet_Check(matcher_value));
  924. if (!_PyBaseExceptionGroup_Check(exc)) {
  925. PyObject *exc_id = PyLong_FromVoidPtr(exc);
  926. if (exc_id == NULL) {
  927. return -1;
  928. }
  929. int res = PySet_Contains(matcher_value, exc_id);
  930. Py_DECREF(exc_id);
  931. return res;
  932. }
  933. return 0;
  934. }
  935. }
  936. return 0;
  937. }
  938. typedef struct {
  939. PyObject *match;
  940. PyObject *rest;
  941. } _exceptiongroup_split_result;
  942. static int
  943. exceptiongroup_split_recursive(PyObject *exc,
  944. _exceptiongroup_split_matcher_type matcher_type,
  945. PyObject *matcher_value,
  946. bool construct_rest,
  947. _exceptiongroup_split_result *result)
  948. {
  949. result->match = NULL;
  950. result->rest = NULL;
  951. int is_match = exceptiongroup_split_check_match(
  952. exc, matcher_type, matcher_value);
  953. if (is_match < 0) {
  954. return -1;
  955. }
  956. if (is_match) {
  957. /* Full match */
  958. result->match = Py_NewRef(exc);
  959. return 0;
  960. }
  961. else if (!_PyBaseExceptionGroup_Check(exc)) {
  962. /* Leaf exception and no match */
  963. if (construct_rest) {
  964. result->rest = Py_NewRef(exc);
  965. }
  966. return 0;
  967. }
  968. /* Partial match */
  969. PyBaseExceptionGroupObject *eg = _PyBaseExceptionGroupObject_cast(exc);
  970. assert(PyTuple_CheckExact(eg->excs));
  971. Py_ssize_t num_excs = PyTuple_Size(eg->excs);
  972. if (num_excs < 0) {
  973. return -1;
  974. }
  975. assert(num_excs > 0); /* checked in constructor, and excs is read-only */
  976. int retval = -1;
  977. PyObject *match_list = PyList_New(0);
  978. if (!match_list) {
  979. return -1;
  980. }
  981. PyObject *rest_list = NULL;
  982. if (construct_rest) {
  983. rest_list = PyList_New(0);
  984. if (!rest_list) {
  985. goto done;
  986. }
  987. }
  988. /* recursive calls */
  989. for (Py_ssize_t i = 0; i < num_excs; i++) {
  990. PyObject *e = PyTuple_GET_ITEM(eg->excs, i);
  991. _exceptiongroup_split_result rec_result;
  992. if (_Py_EnterRecursiveCall(" in exceptiongroup_split_recursive")) {
  993. goto done;
  994. }
  995. if (exceptiongroup_split_recursive(
  996. e, matcher_type, matcher_value,
  997. construct_rest, &rec_result) < 0) {
  998. assert(!rec_result.match);
  999. assert(!rec_result.rest);
  1000. _Py_LeaveRecursiveCall();
  1001. goto done;
  1002. }
  1003. _Py_LeaveRecursiveCall();
  1004. if (rec_result.match) {
  1005. assert(PyList_CheckExact(match_list));
  1006. if (PyList_Append(match_list, rec_result.match) < 0) {
  1007. Py_DECREF(rec_result.match);
  1008. Py_XDECREF(rec_result.rest);
  1009. goto done;
  1010. }
  1011. Py_DECREF(rec_result.match);
  1012. }
  1013. if (rec_result.rest) {
  1014. assert(construct_rest);
  1015. assert(PyList_CheckExact(rest_list));
  1016. if (PyList_Append(rest_list, rec_result.rest) < 0) {
  1017. Py_DECREF(rec_result.rest);
  1018. goto done;
  1019. }
  1020. Py_DECREF(rec_result.rest);
  1021. }
  1022. }
  1023. /* construct result */
  1024. if (exceptiongroup_subset(eg, match_list, &result->match) < 0) {
  1025. goto done;
  1026. }
  1027. if (construct_rest) {
  1028. assert(PyList_CheckExact(rest_list));
  1029. if (exceptiongroup_subset(eg, rest_list, &result->rest) < 0) {
  1030. Py_CLEAR(result->match);
  1031. goto done;
  1032. }
  1033. }
  1034. retval = 0;
  1035. done:
  1036. Py_DECREF(match_list);
  1037. Py_XDECREF(rest_list);
  1038. if (retval < 0) {
  1039. Py_CLEAR(result->match);
  1040. Py_CLEAR(result->rest);
  1041. }
  1042. return retval;
  1043. }
  1044. static PyObject *
  1045. BaseExceptionGroup_split(PyObject *self, PyObject *args)
  1046. {
  1047. PyObject *matcher_value = NULL;
  1048. if (!PyArg_UnpackTuple(args, "split", 1, 1, &matcher_value)) {
  1049. return NULL;
  1050. }
  1051. _exceptiongroup_split_matcher_type matcher_type;
  1052. if (get_matcher_type(matcher_value, &matcher_type) < 0) {
  1053. return NULL;
  1054. }
  1055. _exceptiongroup_split_result split_result;
  1056. bool construct_rest = true;
  1057. if (exceptiongroup_split_recursive(
  1058. self, matcher_type, matcher_value,
  1059. construct_rest, &split_result) < 0) {
  1060. return NULL;
  1061. }
  1062. PyObject *result = PyTuple_Pack(
  1063. 2,
  1064. split_result.match ? split_result.match : Py_None,
  1065. split_result.rest ? split_result.rest : Py_None);
  1066. Py_XDECREF(split_result.match);
  1067. Py_XDECREF(split_result.rest);
  1068. return result;
  1069. }
  1070. static PyObject *
  1071. BaseExceptionGroup_subgroup(PyObject *self, PyObject *args)
  1072. {
  1073. PyObject *matcher_value = NULL;
  1074. if (!PyArg_UnpackTuple(args, "subgroup", 1, 1, &matcher_value)) {
  1075. return NULL;
  1076. }
  1077. _exceptiongroup_split_matcher_type matcher_type;
  1078. if (get_matcher_type(matcher_value, &matcher_type) < 0) {
  1079. return NULL;
  1080. }
  1081. _exceptiongroup_split_result split_result;
  1082. bool construct_rest = false;
  1083. if (exceptiongroup_split_recursive(
  1084. self, matcher_type, matcher_value,
  1085. construct_rest, &split_result) < 0) {
  1086. return NULL;
  1087. }
  1088. PyObject *result = Py_NewRef(
  1089. split_result.match ? split_result.match : Py_None);
  1090. Py_XDECREF(split_result.match);
  1091. assert(!split_result.rest);
  1092. return result;
  1093. }
  1094. static int
  1095. collect_exception_group_leaf_ids(PyObject *exc, PyObject *leaf_ids)
  1096. {
  1097. if (Py_IsNone(exc)) {
  1098. return 0;
  1099. }
  1100. assert(PyExceptionInstance_Check(exc));
  1101. assert(PySet_Check(leaf_ids));
  1102. /* Add IDs of all leaf exceptions in exc to the leaf_ids set */
  1103. if (!_PyBaseExceptionGroup_Check(exc)) {
  1104. PyObject *exc_id = PyLong_FromVoidPtr(exc);
  1105. if (exc_id == NULL) {
  1106. return -1;
  1107. }
  1108. int res = PySet_Add(leaf_ids, exc_id);
  1109. Py_DECREF(exc_id);
  1110. return res;
  1111. }
  1112. PyBaseExceptionGroupObject *eg = _PyBaseExceptionGroupObject_cast(exc);
  1113. Py_ssize_t num_excs = PyTuple_GET_SIZE(eg->excs);
  1114. /* recursive calls */
  1115. for (Py_ssize_t i = 0; i < num_excs; i++) {
  1116. PyObject *e = PyTuple_GET_ITEM(eg->excs, i);
  1117. if (_Py_EnterRecursiveCall(" in collect_exception_group_leaf_ids")) {
  1118. return -1;
  1119. }
  1120. int res = collect_exception_group_leaf_ids(e, leaf_ids);
  1121. _Py_LeaveRecursiveCall();
  1122. if (res < 0) {
  1123. return -1;
  1124. }
  1125. }
  1126. return 0;
  1127. }
  1128. /* This function is used by the interpreter to construct reraised
  1129. * exception groups. It takes an exception group eg and a list
  1130. * of exception groups keep and returns the sub-exception group
  1131. * of eg which contains all leaf exceptions that are contained
  1132. * in any exception group in keep.
  1133. */
  1134. static PyObject *
  1135. exception_group_projection(PyObject *eg, PyObject *keep)
  1136. {
  1137. assert(_PyBaseExceptionGroup_Check(eg));
  1138. assert(PyList_CheckExact(keep));
  1139. PyObject *leaf_ids = PySet_New(NULL);
  1140. if (!leaf_ids) {
  1141. return NULL;
  1142. }
  1143. Py_ssize_t n = PyList_GET_SIZE(keep);
  1144. for (Py_ssize_t i = 0; i < n; i++) {
  1145. PyObject *e = PyList_GET_ITEM(keep, i);
  1146. assert(e != NULL);
  1147. assert(_PyBaseExceptionGroup_Check(e));
  1148. if (collect_exception_group_leaf_ids(e, leaf_ids) < 0) {
  1149. Py_DECREF(leaf_ids);
  1150. return NULL;
  1151. }
  1152. }
  1153. _exceptiongroup_split_result split_result;
  1154. bool construct_rest = false;
  1155. int err = exceptiongroup_split_recursive(
  1156. eg, EXCEPTION_GROUP_MATCH_INSTANCE_IDS, leaf_ids,
  1157. construct_rest, &split_result);
  1158. Py_DECREF(leaf_ids);
  1159. if (err < 0) {
  1160. return NULL;
  1161. }
  1162. PyObject *result = split_result.match ?
  1163. split_result.match : Py_NewRef(Py_None);
  1164. assert(split_result.rest == NULL);
  1165. return result;
  1166. }
  1167. static bool
  1168. is_same_exception_metadata(PyObject *exc1, PyObject *exc2)
  1169. {
  1170. assert(PyExceptionInstance_Check(exc1));
  1171. assert(PyExceptionInstance_Check(exc2));
  1172. PyBaseExceptionObject *e1 = (PyBaseExceptionObject *)exc1;
  1173. PyBaseExceptionObject *e2 = (PyBaseExceptionObject *)exc2;
  1174. return (e1->notes == e2->notes &&
  1175. e1->traceback == e2->traceback &&
  1176. e1->cause == e2->cause &&
  1177. e1->context == e2->context);
  1178. }
  1179. /*
  1180. This function is used by the interpreter to calculate
  1181. the exception group to be raised at the end of a
  1182. try-except* construct.
  1183. orig: the original except that was caught.
  1184. excs: a list of exceptions that were raised/reraised
  1185. in the except* clauses.
  1186. Calculates an exception group to raise. It contains
  1187. all exceptions in excs, where those that were reraised
  1188. have same nesting structure as in orig, and those that
  1189. were raised (if any) are added as siblings in a new EG.
  1190. Returns NULL and sets an exception on failure.
  1191. */
  1192. PyObject *
  1193. _PyExc_PrepReraiseStar(PyObject *orig, PyObject *excs)
  1194. {
  1195. /* orig must be a raised & caught exception, so it has a traceback */
  1196. assert(PyExceptionInstance_Check(orig));
  1197. assert(_PyBaseExceptionObject_cast(orig)->traceback != NULL);
  1198. assert(PyList_Check(excs));
  1199. Py_ssize_t numexcs = PyList_GET_SIZE(excs);
  1200. if (numexcs == 0) {
  1201. return Py_NewRef(Py_None);
  1202. }
  1203. if (!_PyBaseExceptionGroup_Check(orig)) {
  1204. /* a naked exception was caught and wrapped. Only one except* clause
  1205. * could have executed,so there is at most one exception to raise.
  1206. */
  1207. assert(numexcs == 1 || (numexcs == 2 && PyList_GET_ITEM(excs, 1) == Py_None));
  1208. PyObject *e = PyList_GET_ITEM(excs, 0);
  1209. assert(e != NULL);
  1210. return Py_NewRef(e);
  1211. }
  1212. PyObject *raised_list = PyList_New(0);
  1213. if (raised_list == NULL) {
  1214. return NULL;
  1215. }
  1216. PyObject* reraised_list = PyList_New(0);
  1217. if (reraised_list == NULL) {
  1218. Py_DECREF(raised_list);
  1219. return NULL;
  1220. }
  1221. /* Now we are holding refs to raised_list and reraised_list */
  1222. PyObject *result = NULL;
  1223. /* Split excs into raised and reraised by comparing metadata with orig */
  1224. for (Py_ssize_t i = 0; i < numexcs; i++) {
  1225. PyObject *e = PyList_GET_ITEM(excs, i);
  1226. assert(e != NULL);
  1227. if (Py_IsNone(e)) {
  1228. continue;
  1229. }
  1230. bool is_reraise = is_same_exception_metadata(e, orig);
  1231. PyObject *append_list = is_reraise ? reraised_list : raised_list;
  1232. if (PyList_Append(append_list, e) < 0) {
  1233. goto done;
  1234. }
  1235. }
  1236. PyObject *reraised_eg = exception_group_projection(orig, reraised_list);
  1237. if (reraised_eg == NULL) {
  1238. goto done;
  1239. }
  1240. if (!Py_IsNone(reraised_eg)) {
  1241. assert(is_same_exception_metadata(reraised_eg, orig));
  1242. }
  1243. Py_ssize_t num_raised = PyList_GET_SIZE(raised_list);
  1244. if (num_raised == 0) {
  1245. result = reraised_eg;
  1246. }
  1247. else if (num_raised > 0) {
  1248. int res = 0;
  1249. if (!Py_IsNone(reraised_eg)) {
  1250. res = PyList_Append(raised_list, reraised_eg);
  1251. }
  1252. Py_DECREF(reraised_eg);
  1253. if (res < 0) {
  1254. goto done;
  1255. }
  1256. if (PyList_GET_SIZE(raised_list) > 1) {
  1257. result = _PyExc_CreateExceptionGroup("", raised_list);
  1258. }
  1259. else {
  1260. result = Py_NewRef(PyList_GetItem(raised_list, 0));
  1261. }
  1262. if (result == NULL) {
  1263. goto done;
  1264. }
  1265. }
  1266. done:
  1267. Py_XDECREF(raised_list);
  1268. Py_XDECREF(reraised_list);
  1269. return result;
  1270. }
  1271. PyObject *
  1272. PyUnstable_Exc_PrepReraiseStar(PyObject *orig, PyObject *excs)
  1273. {
  1274. if (orig == NULL || !PyExceptionInstance_Check(orig)) {
  1275. PyErr_SetString(PyExc_TypeError, "orig must be an exception instance");
  1276. return NULL;
  1277. }
  1278. if (excs == NULL || !PyList_Check(excs)) {
  1279. PyErr_SetString(PyExc_TypeError,
  1280. "excs must be a list of exception instances");
  1281. return NULL;
  1282. }
  1283. Py_ssize_t numexcs = PyList_GET_SIZE(excs);
  1284. for (Py_ssize_t i = 0; i < numexcs; i++) {
  1285. PyObject *exc = PyList_GET_ITEM(excs, i);
  1286. if (exc == NULL || !(PyExceptionInstance_Check(exc) || Py_IsNone(exc))) {
  1287. PyErr_Format(PyExc_TypeError,
  1288. "item %d of excs is not an exception", i);
  1289. return NULL;
  1290. }
  1291. }
  1292. /* Make sure that orig has something as traceback, in the interpreter
  1293. * it always does becuase it's a raised exception.
  1294. */
  1295. PyObject *tb = PyException_GetTraceback(orig);
  1296. if (tb == NULL) {
  1297. PyErr_Format(PyExc_ValueError, "orig must be a raised exception");
  1298. return NULL;
  1299. }
  1300. Py_DECREF(tb);
  1301. return _PyExc_PrepReraiseStar(orig, excs);
  1302. }
  1303. static PyMemberDef BaseExceptionGroup_members[] = {
  1304. {"message", T_OBJECT, offsetof(PyBaseExceptionGroupObject, msg), READONLY,
  1305. PyDoc_STR("exception message")},
  1306. {"exceptions", T_OBJECT, offsetof(PyBaseExceptionGroupObject, excs), READONLY,
  1307. PyDoc_STR("nested exceptions")},
  1308. {NULL} /* Sentinel */
  1309. };
  1310. static PyMethodDef BaseExceptionGroup_methods[] = {
  1311. {"__class_getitem__", (PyCFunction)Py_GenericAlias,
  1312. METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
  1313. {"derive", (PyCFunction)BaseExceptionGroup_derive, METH_VARARGS},
  1314. {"split", (PyCFunction)BaseExceptionGroup_split, METH_VARARGS},
  1315. {"subgroup", (PyCFunction)BaseExceptionGroup_subgroup, METH_VARARGS},
  1316. {NULL}
  1317. };
  1318. ComplexExtendsException(PyExc_BaseException, BaseExceptionGroup,
  1319. BaseExceptionGroup, BaseExceptionGroup_new /* new */,
  1320. BaseExceptionGroup_methods, BaseExceptionGroup_members,
  1321. 0 /* getset */, BaseExceptionGroup_str,
  1322. "A combination of multiple unrelated exceptions.");
  1323. /*
  1324. * ExceptionGroup extends BaseExceptionGroup, Exception
  1325. */
  1326. static PyObject*
  1327. create_exception_group_class(void) {
  1328. struct _Py_exc_state *state = get_exc_state();
  1329. PyObject *bases = PyTuple_Pack(
  1330. 2, PyExc_BaseExceptionGroup, PyExc_Exception);
  1331. if (bases == NULL) {
  1332. return NULL;
  1333. }
  1334. assert(!state->PyExc_ExceptionGroup);
  1335. state->PyExc_ExceptionGroup = PyErr_NewException(
  1336. "builtins.ExceptionGroup", bases, NULL);
  1337. Py_DECREF(bases);
  1338. return state->PyExc_ExceptionGroup;
  1339. }
  1340. /*
  1341. * KeyboardInterrupt extends BaseException
  1342. */
  1343. SimpleExtendsException(PyExc_BaseException, KeyboardInterrupt,
  1344. "Program interrupted by user.");
  1345. /*
  1346. * ImportError extends Exception
  1347. */
  1348. static int
  1349. ImportError_init(PyImportErrorObject *self, PyObject *args, PyObject *kwds)
  1350. {
  1351. static char *kwlist[] = {"name", "path", "name_from", 0};
  1352. PyObject *empty_tuple;
  1353. PyObject *msg = NULL;
  1354. PyObject *name = NULL;
  1355. PyObject *path = NULL;
  1356. PyObject *name_from = NULL;
  1357. if (BaseException_init((PyBaseExceptionObject *)self, args, NULL) == -1)
  1358. return -1;
  1359. empty_tuple = PyTuple_New(0);
  1360. if (!empty_tuple)
  1361. return -1;
  1362. if (!PyArg_ParseTupleAndKeywords(empty_tuple, kwds, "|$OOO:ImportError", kwlist,
  1363. &name, &path, &name_from)) {
  1364. Py_DECREF(empty_tuple);
  1365. return -1;
  1366. }
  1367. Py_DECREF(empty_tuple);
  1368. Py_XSETREF(self->name, Py_XNewRef(name));
  1369. Py_XSETREF(self->path, Py_XNewRef(path));
  1370. Py_XSETREF(self->name_from, Py_XNewRef(name_from));
  1371. if (PyTuple_GET_SIZE(args) == 1) {
  1372. msg = Py_NewRef(PyTuple_GET_ITEM(args, 0));
  1373. }
  1374. Py_XSETREF(self->msg, msg);
  1375. return 0;
  1376. }
  1377. static int
  1378. ImportError_clear(PyImportErrorObject *self)
  1379. {
  1380. Py_CLEAR(self->msg);
  1381. Py_CLEAR(self->name);
  1382. Py_CLEAR(self->path);
  1383. Py_CLEAR(self->name_from);
  1384. return BaseException_clear((PyBaseExceptionObject *)self);
  1385. }
  1386. static void
  1387. ImportError_dealloc(PyImportErrorObject *self)
  1388. {
  1389. _PyObject_GC_UNTRACK(self);
  1390. ImportError_clear(self);
  1391. Py_TYPE(self)->tp_free((PyObject *)self);
  1392. }
  1393. static int
  1394. ImportError_traverse(PyImportErrorObject *self, visitproc visit, void *arg)
  1395. {
  1396. Py_VISIT(self->msg);
  1397. Py_VISIT(self->name);
  1398. Py_VISIT(self->path);
  1399. Py_VISIT(self->name_from);
  1400. return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
  1401. }
  1402. static PyObject *
  1403. ImportError_str(PyImportErrorObject *self)
  1404. {
  1405. if (self->msg && PyUnicode_CheckExact(self->msg)) {
  1406. return Py_NewRef(self->msg);
  1407. }
  1408. else {
  1409. return BaseException_str((PyBaseExceptionObject *)self);
  1410. }
  1411. }
  1412. static PyObject *
  1413. ImportError_getstate(PyImportErrorObject *self)
  1414. {
  1415. PyObject *dict = ((PyBaseExceptionObject *)self)->dict;
  1416. if (self->name || self->path || self->name_from) {
  1417. dict = dict ? PyDict_Copy(dict) : PyDict_New();
  1418. if (dict == NULL)
  1419. return NULL;
  1420. if (self->name && PyDict_SetItem(dict, &_Py_ID(name), self->name) < 0) {
  1421. Py_DECREF(dict);
  1422. return NULL;
  1423. }
  1424. if (self->path && PyDict_SetItem(dict, &_Py_ID(path), self->path) < 0) {
  1425. Py_DECREF(dict);
  1426. return NULL;
  1427. }
  1428. if (self->name_from && PyDict_SetItem(dict, &_Py_ID(name_from), self->name_from) < 0) {
  1429. Py_DECREF(dict);
  1430. return NULL;
  1431. }
  1432. return dict;
  1433. }
  1434. else if (dict) {
  1435. return Py_NewRef(dict);
  1436. }
  1437. else {
  1438. Py_RETURN_NONE;
  1439. }
  1440. }
  1441. /* Pickling support */
  1442. static PyObject *
  1443. ImportError_reduce(PyImportErrorObject *self, PyObject *Py_UNUSED(ignored))
  1444. {
  1445. PyObject *res;
  1446. PyObject *args;
  1447. PyObject *state = ImportError_getstate(self);
  1448. if (state == NULL)
  1449. return NULL;
  1450. args = ((PyBaseExceptionObject *)self)->args;
  1451. if (state == Py_None)
  1452. res = PyTuple_Pack(2, Py_TYPE(self), args);
  1453. else
  1454. res = PyTuple_Pack(3, Py_TYPE(self), args, state);
  1455. Py_DECREF(state);
  1456. return res;
  1457. }
  1458. static PyMemberDef ImportError_members[] = {
  1459. {"msg", T_OBJECT, offsetof(PyImportErrorObject, msg), 0,
  1460. PyDoc_STR("exception message")},
  1461. {"name", T_OBJECT, offsetof(PyImportErrorObject, name), 0,
  1462. PyDoc_STR("module name")},
  1463. {"path", T_OBJECT, offsetof(PyImportErrorObject, path), 0,
  1464. PyDoc_STR("module path")},
  1465. {"name_from", T_OBJECT, offsetof(PyImportErrorObject, name_from), 0,
  1466. PyDoc_STR("name imported from module")},
  1467. {NULL} /* Sentinel */
  1468. };
  1469. static PyMethodDef ImportError_methods[] = {
  1470. {"__reduce__", (PyCFunction)ImportError_reduce, METH_NOARGS},
  1471. {NULL}
  1472. };
  1473. ComplexExtendsException(PyExc_Exception, ImportError,
  1474. ImportError, 0 /* new */,
  1475. ImportError_methods, ImportError_members,
  1476. 0 /* getset */, ImportError_str,
  1477. "Import can't find module, or can't find name in "
  1478. "module.");
  1479. /*
  1480. * ModuleNotFoundError extends ImportError
  1481. */
  1482. MiddlingExtendsException(PyExc_ImportError, ModuleNotFoundError, ImportError,
  1483. "Module not found.");
  1484. /*
  1485. * OSError extends Exception
  1486. */
  1487. #ifdef MS_WINDOWS
  1488. #include "errmap.h"
  1489. #endif
  1490. /* Where a function has a single filename, such as open() or some
  1491. * of the os module functions, PyErr_SetFromErrnoWithFilename() is
  1492. * called, giving a third argument which is the filename. But, so
  1493. * that old code using in-place unpacking doesn't break, e.g.:
  1494. *
  1495. * except OSError, (errno, strerror):
  1496. *
  1497. * we hack args so that it only contains two items. This also
  1498. * means we need our own __str__() which prints out the filename
  1499. * when it was supplied.
  1500. *
  1501. * (If a function has two filenames, such as rename(), symlink(),
  1502. * or copy(), PyErr_SetFromErrnoWithFilenameObjects() is called,
  1503. * which allows passing in a second filename.)
  1504. */
  1505. /* This function doesn't cleanup on error, the caller should */
  1506. static int
  1507. oserror_parse_args(PyObject **p_args,
  1508. PyObject **myerrno, PyObject **strerror,
  1509. PyObject **filename, PyObject **filename2
  1510. #ifdef MS_WINDOWS
  1511. , PyObject **winerror
  1512. #endif
  1513. )
  1514. {
  1515. Py_ssize_t nargs;
  1516. PyObject *args = *p_args;
  1517. #ifndef MS_WINDOWS
  1518. /*
  1519. * ignored on non-Windows platforms,
  1520. * but parsed so OSError has a consistent signature
  1521. */
  1522. PyObject *_winerror = NULL;
  1523. PyObject **winerror = &_winerror;
  1524. #endif /* MS_WINDOWS */
  1525. nargs = PyTuple_GET_SIZE(args);
  1526. if (nargs >= 2 && nargs <= 5) {
  1527. if (!PyArg_UnpackTuple(args, "OSError", 2, 5,
  1528. myerrno, strerror,
  1529. filename, winerror, filename2))
  1530. return -1;
  1531. #ifdef MS_WINDOWS
  1532. if (*winerror && PyLong_Check(*winerror)) {
  1533. long errcode, winerrcode;
  1534. PyObject *newargs;
  1535. Py_ssize_t i;
  1536. winerrcode = PyLong_AsLong(*winerror);
  1537. if (winerrcode == -1 && PyErr_Occurred())
  1538. return -1;
  1539. errcode = winerror_to_errno(winerrcode);
  1540. *myerrno = PyLong_FromLong(errcode);
  1541. if (!*myerrno)
  1542. return -1;
  1543. newargs = PyTuple_New(nargs);
  1544. if (!newargs)
  1545. return -1;
  1546. PyTuple_SET_ITEM(newargs, 0, *myerrno);
  1547. for (i = 1; i < nargs; i++) {
  1548. PyObject *val = PyTuple_GET_ITEM(args, i);
  1549. PyTuple_SET_ITEM(newargs, i, Py_NewRef(val));
  1550. }
  1551. Py_DECREF(args);
  1552. args = *p_args = newargs;
  1553. }
  1554. #endif /* MS_WINDOWS */
  1555. }
  1556. return 0;
  1557. }
  1558. static int
  1559. oserror_init(PyOSErrorObject *self, PyObject **p_args,
  1560. PyObject *myerrno, PyObject *strerror,
  1561. PyObject *filename, PyObject *filename2
  1562. #ifdef MS_WINDOWS
  1563. , PyObject *winerror
  1564. #endif
  1565. )
  1566. {
  1567. PyObject *args = *p_args;
  1568. Py_ssize_t nargs = PyTuple_GET_SIZE(args);
  1569. /* self->filename will remain Py_None otherwise */
  1570. if (filename && filename != Py_None) {
  1571. if (Py_IS_TYPE(self, (PyTypeObject *) PyExc_BlockingIOError) &&
  1572. PyNumber_Check(filename)) {
  1573. /* BlockingIOError's 3rd argument can be the number of
  1574. * characters written.
  1575. */
  1576. self->written = PyNumber_AsSsize_t(filename, PyExc_ValueError);
  1577. if (self->written == -1 && PyErr_Occurred())
  1578. return -1;
  1579. }
  1580. else {
  1581. self->filename = Py_NewRef(filename);
  1582. if (filename2 && filename2 != Py_None) {
  1583. self->filename2 = Py_NewRef(filename2);
  1584. }
  1585. if (nargs >= 2 && nargs <= 5) {
  1586. /* filename, filename2, and winerror are removed from the args tuple
  1587. (for compatibility purposes, see test_exceptions.py) */
  1588. PyObject *subslice = PyTuple_GetSlice(args, 0, 2);
  1589. if (!subslice)
  1590. return -1;
  1591. Py_DECREF(args); /* replacing args */
  1592. *p_args = args = subslice;
  1593. }
  1594. }
  1595. }
  1596. self->myerrno = Py_XNewRef(myerrno);
  1597. self->strerror = Py_XNewRef(strerror);
  1598. #ifdef MS_WINDOWS
  1599. self->winerror = Py_XNewRef(winerror);
  1600. #endif
  1601. /* Steals the reference to args */
  1602. Py_XSETREF(self->args, args);
  1603. *p_args = args = NULL;
  1604. return 0;
  1605. }
  1606. static PyObject *
  1607. OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
  1608. static int
  1609. OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds);
  1610. static int
  1611. oserror_use_init(PyTypeObject *type)
  1612. {
  1613. /* When __init__ is defined in an OSError subclass, we want any
  1614. extraneous argument to __new__ to be ignored. The only reasonable
  1615. solution, given __new__ takes a variable number of arguments,
  1616. is to defer arg parsing and initialization to __init__.
  1617. But when __new__ is overridden as well, it should call our __new__
  1618. with the right arguments.
  1619. (see http://bugs.python.org/issue12555#msg148829 )
  1620. */
  1621. if (type->tp_init != (initproc) OSError_init &&
  1622. type->tp_new == (newfunc) OSError_new) {
  1623. assert((PyObject *) type != PyExc_OSError);
  1624. return 1;
  1625. }
  1626. return 0;
  1627. }
  1628. static PyObject *
  1629. OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  1630. {
  1631. PyOSErrorObject *self = NULL;
  1632. PyObject *myerrno = NULL, *strerror = NULL;
  1633. PyObject *filename = NULL, *filename2 = NULL;
  1634. #ifdef MS_WINDOWS
  1635. PyObject *winerror = NULL;
  1636. #endif
  1637. Py_INCREF(args);
  1638. if (!oserror_use_init(type)) {
  1639. if (!_PyArg_NoKeywords(type->tp_name, kwds))
  1640. goto error;
  1641. if (oserror_parse_args(&args, &myerrno, &strerror,
  1642. &filename, &filename2
  1643. #ifdef MS_WINDOWS
  1644. , &winerror
  1645. #endif
  1646. ))
  1647. goto error;
  1648. struct _Py_exc_state *state = get_exc_state();
  1649. if (myerrno && PyLong_Check(myerrno) &&
  1650. state->errnomap && (PyObject *) type == PyExc_OSError) {
  1651. PyObject *newtype;
  1652. newtype = PyDict_GetItemWithError(state->errnomap, myerrno);
  1653. if (newtype) {
  1654. type = _PyType_CAST(newtype);
  1655. }
  1656. else if (PyErr_Occurred())
  1657. goto error;
  1658. }
  1659. }
  1660. self = (PyOSErrorObject *) type->tp_alloc(type, 0);
  1661. if (!self)
  1662. goto error;
  1663. self->dict = NULL;
  1664. self->traceback = self->cause = self->context = NULL;
  1665. self->written = -1;
  1666. if (!oserror_use_init(type)) {
  1667. if (oserror_init(self, &args, myerrno, strerror, filename, filename2
  1668. #ifdef MS_WINDOWS
  1669. , winerror
  1670. #endif
  1671. ))
  1672. goto error;
  1673. }
  1674. else {
  1675. self->args = PyTuple_New(0);
  1676. if (self->args == NULL)
  1677. goto error;
  1678. }
  1679. Py_XDECREF(args);
  1680. return (PyObject *) self;
  1681. error:
  1682. Py_XDECREF(args);
  1683. Py_XDECREF(self);
  1684. return NULL;
  1685. }
  1686. static int
  1687. OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds)
  1688. {
  1689. PyObject *myerrno = NULL, *strerror = NULL;
  1690. PyObject *filename = NULL, *filename2 = NULL;
  1691. #ifdef MS_WINDOWS
  1692. PyObject *winerror = NULL;
  1693. #endif
  1694. if (!oserror_use_init(Py_TYPE(self)))
  1695. /* Everything already done in OSError_new */
  1696. return 0;
  1697. if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
  1698. return -1;
  1699. Py_INCREF(args);
  1700. if (oserror_parse_args(&args, &myerrno, &strerror, &filename, &filename2
  1701. #ifdef MS_WINDOWS
  1702. , &winerror
  1703. #endif
  1704. ))
  1705. goto error;
  1706. if (oserror_init(self, &args, myerrno, strerror, filename, filename2
  1707. #ifdef MS_WINDOWS
  1708. , winerror
  1709. #endif
  1710. ))
  1711. goto error;
  1712. return 0;
  1713. error:
  1714. Py_DECREF(args);
  1715. return -1;
  1716. }
  1717. static int
  1718. OSError_clear(PyOSErrorObject *self)
  1719. {
  1720. Py_CLEAR(self->myerrno);
  1721. Py_CLEAR(self->strerror);
  1722. Py_CLEAR(self->filename);
  1723. Py_CLEAR(self->filename2);
  1724. #ifdef MS_WINDOWS
  1725. Py_CLEAR(self->winerror);
  1726. #endif
  1727. return BaseException_clear((PyBaseExceptionObject *)self);
  1728. }
  1729. static void
  1730. OSError_dealloc(PyOSErrorObject *self)
  1731. {
  1732. _PyObject_GC_UNTRACK(self);
  1733. OSError_clear(self);
  1734. Py_TYPE(self)->tp_free((PyObject *)self);
  1735. }
  1736. static int
  1737. OSError_traverse(PyOSErrorObject *self, visitproc visit,
  1738. void *arg)
  1739. {
  1740. Py_VISIT(self->myerrno);
  1741. Py_VISIT(self->strerror);
  1742. Py_VISIT(self->filename);
  1743. Py_VISIT(self->filename2);
  1744. #ifdef MS_WINDOWS
  1745. Py_VISIT(self->winerror);
  1746. #endif
  1747. return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
  1748. }
  1749. static PyObject *
  1750. OSError_str(PyOSErrorObject *self)
  1751. {
  1752. #define OR_NONE(x) ((x)?(x):Py_None)
  1753. #ifdef MS_WINDOWS
  1754. /* If available, winerror has the priority over myerrno */
  1755. if (self->winerror && self->filename) {
  1756. if (self->filename2) {
  1757. return PyUnicode_FromFormat("[WinError %S] %S: %R -> %R",
  1758. OR_NONE(self->winerror),
  1759. OR_NONE(self->strerror),
  1760. self->filename,
  1761. self->filename2);
  1762. } else {
  1763. return PyUnicode_FromFormat("[WinError %S] %S: %R",
  1764. OR_NONE(self->winerror),
  1765. OR_NONE(self->strerror),
  1766. self->filename);
  1767. }
  1768. }
  1769. if (self->winerror && self->strerror)
  1770. return PyUnicode_FromFormat("[WinError %S] %S",
  1771. self->winerror ? self->winerror: Py_None,
  1772. self->strerror ? self->strerror: Py_None);
  1773. #endif
  1774. if (self->filename) {
  1775. if (self->filename2) {
  1776. return PyUnicode_FromFormat("[Errno %S] %S: %R -> %R",
  1777. OR_NONE(self->myerrno),
  1778. OR_NONE(self->strerror),
  1779. self->filename,
  1780. self->filename2);
  1781. } else {
  1782. return PyUnicode_FromFormat("[Errno %S] %S: %R",
  1783. OR_NONE(self->myerrno),
  1784. OR_NONE(self->strerror),
  1785. self->filename);
  1786. }
  1787. }
  1788. if (self->myerrno && self->strerror)
  1789. return PyUnicode_FromFormat("[Errno %S] %S",
  1790. self->myerrno, self->strerror);
  1791. return BaseException_str((PyBaseExceptionObject *)self);
  1792. }
  1793. static PyObject *
  1794. OSError_reduce(PyOSErrorObject *self, PyObject *Py_UNUSED(ignored))
  1795. {
  1796. PyObject *args = self->args;
  1797. PyObject *res = NULL;
  1798. /* self->args is only the first two real arguments if there was a
  1799. * file name given to OSError. */
  1800. if (PyTuple_GET_SIZE(args) == 2 && self->filename) {
  1801. Py_ssize_t size = self->filename2 ? 5 : 3;
  1802. args = PyTuple_New(size);
  1803. if (!args)
  1804. return NULL;
  1805. PyTuple_SET_ITEM(args, 0, Py_NewRef(PyTuple_GET_ITEM(self->args, 0)));
  1806. PyTuple_SET_ITEM(args, 1, Py_NewRef(PyTuple_GET_ITEM(self->args, 1)));
  1807. PyTuple_SET_ITEM(args, 2, Py_NewRef(self->filename));
  1808. if (self->filename2) {
  1809. /*
  1810. * This tuple is essentially used as OSError(*args).
  1811. * So, to recreate filename2, we need to pass in
  1812. * winerror as well.
  1813. */
  1814. PyTuple_SET_ITEM(args, 3, Py_NewRef(Py_None));
  1815. /* filename2 */
  1816. PyTuple_SET_ITEM(args, 4, Py_NewRef(self->filename2));
  1817. }
  1818. } else
  1819. Py_INCREF(args);
  1820. if (self->dict)
  1821. res = PyTuple_Pack(3, Py_TYPE(self), args, self->dict);
  1822. else
  1823. res = PyTuple_Pack(2, Py_TYPE(self), args);
  1824. Py_DECREF(args);
  1825. return res;
  1826. }
  1827. static PyObject *
  1828. OSError_written_get(PyOSErrorObject *self, void *context)
  1829. {
  1830. if (self->written == -1) {
  1831. PyErr_SetString(PyExc_AttributeError, "characters_written");
  1832. return NULL;
  1833. }
  1834. return PyLong_FromSsize_t(self->written);
  1835. }
  1836. static int
  1837. OSError_written_set(PyOSErrorObject *self, PyObject *arg, void *context)
  1838. {
  1839. if (arg == NULL) {
  1840. if (self->written == -1) {
  1841. PyErr_SetString(PyExc_AttributeError, "characters_written");
  1842. return -1;
  1843. }
  1844. self->written = -1;
  1845. return 0;
  1846. }
  1847. Py_ssize_t n;
  1848. n = PyNumber_AsSsize_t(arg, PyExc_ValueError);
  1849. if (n == -1 && PyErr_Occurred())
  1850. return -1;
  1851. self->written = n;
  1852. return 0;
  1853. }
  1854. static PyMemberDef OSError_members[] = {
  1855. {"errno", T_OBJECT, offsetof(PyOSErrorObject, myerrno), 0,
  1856. PyDoc_STR("POSIX exception code")},
  1857. {"strerror", T_OBJECT, offsetof(PyOSErrorObject, strerror), 0,
  1858. PyDoc_STR("exception strerror")},
  1859. {"filename", T_OBJECT, offsetof(PyOSErrorObject, filename), 0,
  1860. PyDoc_STR("exception filename")},
  1861. {"filename2", T_OBJECT, offsetof(PyOSErrorObject, filename2), 0,
  1862. PyDoc_STR("second exception filename")},
  1863. #ifdef MS_WINDOWS
  1864. {"winerror", T_OBJECT, offsetof(PyOSErrorObject, winerror), 0,
  1865. PyDoc_STR("Win32 exception code")},
  1866. #endif
  1867. {NULL} /* Sentinel */
  1868. };
  1869. static PyMethodDef OSError_methods[] = {
  1870. {"__reduce__", (PyCFunction)OSError_reduce, METH_NOARGS},
  1871. {NULL}
  1872. };
  1873. static PyGetSetDef OSError_getset[] = {
  1874. {"characters_written", (getter) OSError_written_get,
  1875. (setter) OSError_written_set, NULL},
  1876. {NULL}
  1877. };
  1878. ComplexExtendsException(PyExc_Exception, OSError,
  1879. OSError, OSError_new,
  1880. OSError_methods, OSError_members, OSError_getset,
  1881. OSError_str,
  1882. "Base class for I/O related errors.");
  1883. /*
  1884. * Various OSError subclasses
  1885. */
  1886. MiddlingExtendsException(PyExc_OSError, BlockingIOError, OSError,
  1887. "I/O operation would block.");
  1888. MiddlingExtendsException(PyExc_OSError, ConnectionError, OSError,
  1889. "Connection error.");
  1890. MiddlingExtendsException(PyExc_OSError, ChildProcessError, OSError,
  1891. "Child process error.");
  1892. MiddlingExtendsException(PyExc_ConnectionError, BrokenPipeError, OSError,
  1893. "Broken pipe.");
  1894. MiddlingExtendsException(PyExc_ConnectionError, ConnectionAbortedError, OSError,
  1895. "Connection aborted.");
  1896. MiddlingExtendsException(PyExc_ConnectionError, ConnectionRefusedError, OSError,
  1897. "Connection refused.");
  1898. MiddlingExtendsException(PyExc_ConnectionError, ConnectionResetError, OSError,
  1899. "Connection reset.");
  1900. MiddlingExtendsException(PyExc_OSError, FileExistsError, OSError,
  1901. "File already exists.");
  1902. MiddlingExtendsException(PyExc_OSError, FileNotFoundError, OSError,
  1903. "File not found.");
  1904. MiddlingExtendsException(PyExc_OSError, IsADirectoryError, OSError,
  1905. "Operation doesn't work on directories.");
  1906. MiddlingExtendsException(PyExc_OSError, NotADirectoryError, OSError,
  1907. "Operation only works on directories.");
  1908. MiddlingExtendsException(PyExc_OSError, InterruptedError, OSError,
  1909. "Interrupted by signal.");
  1910. MiddlingExtendsException(PyExc_OSError, PermissionError, OSError,
  1911. "Not enough permissions.");
  1912. MiddlingExtendsException(PyExc_OSError, ProcessLookupError, OSError,
  1913. "Process not found.");
  1914. MiddlingExtendsException(PyExc_OSError, TimeoutError, OSError,
  1915. "Timeout expired.");
  1916. /*
  1917. * EOFError extends Exception
  1918. */
  1919. SimpleExtendsException(PyExc_Exception, EOFError,
  1920. "Read beyond end of file.");
  1921. /*
  1922. * RuntimeError extends Exception
  1923. */
  1924. SimpleExtendsException(PyExc_Exception, RuntimeError,
  1925. "Unspecified run-time error.");
  1926. /*
  1927. * RecursionError extends RuntimeError
  1928. */
  1929. SimpleExtendsException(PyExc_RuntimeError, RecursionError,
  1930. "Recursion limit exceeded.");
  1931. /*
  1932. * NotImplementedError extends RuntimeError
  1933. */
  1934. SimpleExtendsException(PyExc_RuntimeError, NotImplementedError,
  1935. "Method or function hasn't been implemented yet.");
  1936. /*
  1937. * NameError extends Exception
  1938. */
  1939. static int
  1940. NameError_init(PyNameErrorObject *self, PyObject *args, PyObject *kwds)
  1941. {
  1942. static char *kwlist[] = {"name", NULL};
  1943. PyObject *name = NULL;
  1944. if (BaseException_init((PyBaseExceptionObject *)self, args, NULL) == -1) {
  1945. return -1;
  1946. }
  1947. PyObject *empty_tuple = PyTuple_New(0);
  1948. if (!empty_tuple) {
  1949. return -1;
  1950. }
  1951. if (!PyArg_ParseTupleAndKeywords(empty_tuple, kwds, "|$O:NameError", kwlist,
  1952. &name)) {
  1953. Py_DECREF(empty_tuple);
  1954. return -1;
  1955. }
  1956. Py_DECREF(empty_tuple);
  1957. Py_XSETREF(self->name, Py_XNewRef(name));
  1958. return 0;
  1959. }
  1960. static int
  1961. NameError_clear(PyNameErrorObject *self)
  1962. {
  1963. Py_CLEAR(self->name);
  1964. return BaseException_clear((PyBaseExceptionObject *)self);
  1965. }
  1966. static void
  1967. NameError_dealloc(PyNameErrorObject *self)
  1968. {
  1969. _PyObject_GC_UNTRACK(self);
  1970. NameError_clear(self);
  1971. Py_TYPE(self)->tp_free((PyObject *)self);
  1972. }
  1973. static int
  1974. NameError_traverse(PyNameErrorObject *self, visitproc visit, void *arg)
  1975. {
  1976. Py_VISIT(self->name);
  1977. return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
  1978. }
  1979. static PyMemberDef NameError_members[] = {
  1980. {"name", T_OBJECT, offsetof(PyNameErrorObject, name), 0, PyDoc_STR("name")},
  1981. {NULL} /* Sentinel */
  1982. };
  1983. static PyMethodDef NameError_methods[] = {
  1984. {NULL} /* Sentinel */
  1985. };
  1986. ComplexExtendsException(PyExc_Exception, NameError,
  1987. NameError, 0,
  1988. NameError_methods, NameError_members,
  1989. 0, BaseException_str, "Name not found globally.");
  1990. /*
  1991. * UnboundLocalError extends NameError
  1992. */
  1993. MiddlingExtendsException(PyExc_NameError, UnboundLocalError, NameError,
  1994. "Local name referenced but not bound to a value.");
  1995. /*
  1996. * AttributeError extends Exception
  1997. */
  1998. static int
  1999. AttributeError_init(PyAttributeErrorObject *self, PyObject *args, PyObject *kwds)
  2000. {
  2001. static char *kwlist[] = {"name", "obj", NULL};
  2002. PyObject *name = NULL;
  2003. PyObject *obj = NULL;
  2004. if (BaseException_init((PyBaseExceptionObject *)self, args, NULL) == -1) {
  2005. return -1;
  2006. }
  2007. PyObject *empty_tuple = PyTuple_New(0);
  2008. if (!empty_tuple) {
  2009. return -1;
  2010. }
  2011. if (!PyArg_ParseTupleAndKeywords(empty_tuple, kwds, "|$OO:AttributeError", kwlist,
  2012. &name, &obj)) {
  2013. Py_DECREF(empty_tuple);
  2014. return -1;
  2015. }
  2016. Py_DECREF(empty_tuple);
  2017. Py_XSETREF(self->name, Py_XNewRef(name));
  2018. Py_XSETREF(self->obj, Py_XNewRef(obj));
  2019. return 0;
  2020. }
  2021. static int
  2022. AttributeError_clear(PyAttributeErrorObject *self)
  2023. {
  2024. Py_CLEAR(self->obj);
  2025. Py_CLEAR(self->name);
  2026. return BaseException_clear((PyBaseExceptionObject *)self);
  2027. }
  2028. static void
  2029. AttributeError_dealloc(PyAttributeErrorObject *self)
  2030. {
  2031. _PyObject_GC_UNTRACK(self);
  2032. AttributeError_clear(self);
  2033. Py_TYPE(self)->tp_free((PyObject *)self);
  2034. }
  2035. static int
  2036. AttributeError_traverse(PyAttributeErrorObject *self, visitproc visit, void *arg)
  2037. {
  2038. Py_VISIT(self->obj);
  2039. Py_VISIT(self->name);
  2040. return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
  2041. }
  2042. /* Pickling support */
  2043. static PyObject *
  2044. AttributeError_getstate(PyAttributeErrorObject *self, PyObject *Py_UNUSED(ignored))
  2045. {
  2046. PyObject *dict = ((PyAttributeErrorObject *)self)->dict;
  2047. if (self->name || self->args) {
  2048. dict = dict ? PyDict_Copy(dict) : PyDict_New();
  2049. if (dict == NULL) {
  2050. return NULL;
  2051. }
  2052. if (self->name && PyDict_SetItemString(dict, "name", self->name) < 0) {
  2053. Py_DECREF(dict);
  2054. return NULL;
  2055. }
  2056. /* We specifically are not pickling the obj attribute since there are many
  2057. cases where it is unlikely to be picklable. See GH-103352.
  2058. */
  2059. if (self->args && PyDict_SetItemString(dict, "args", self->args) < 0) {
  2060. Py_DECREF(dict);
  2061. return NULL;
  2062. }
  2063. return dict;
  2064. }
  2065. else if (dict) {
  2066. return Py_NewRef(dict);
  2067. }
  2068. Py_RETURN_NONE;
  2069. }
  2070. static PyObject *
  2071. AttributeError_reduce(PyAttributeErrorObject *self, PyObject *Py_UNUSED(ignored))
  2072. {
  2073. PyObject *state = AttributeError_getstate(self, NULL);
  2074. if (state == NULL) {
  2075. return NULL;
  2076. }
  2077. PyObject *return_value = PyTuple_Pack(3, Py_TYPE(self), self->args, state);
  2078. Py_DECREF(state);
  2079. return return_value;
  2080. }
  2081. static PyMemberDef AttributeError_members[] = {
  2082. {"name", T_OBJECT, offsetof(PyAttributeErrorObject, name), 0, PyDoc_STR("attribute name")},
  2083. {"obj", T_OBJECT, offsetof(PyAttributeErrorObject, obj), 0, PyDoc_STR("object")},
  2084. {NULL} /* Sentinel */
  2085. };
  2086. static PyMethodDef AttributeError_methods[] = {
  2087. {"__getstate__", (PyCFunction)AttributeError_getstate, METH_NOARGS},
  2088. {"__reduce__", (PyCFunction)AttributeError_reduce, METH_NOARGS },
  2089. {NULL}
  2090. };
  2091. ComplexExtendsException(PyExc_Exception, AttributeError,
  2092. AttributeError, 0,
  2093. AttributeError_methods, AttributeError_members,
  2094. 0, BaseException_str, "Attribute not found.");
  2095. /*
  2096. * SyntaxError extends Exception
  2097. */
  2098. static int
  2099. SyntaxError_init(PySyntaxErrorObject *self, PyObject *args, PyObject *kwds)
  2100. {
  2101. PyObject *info = NULL;
  2102. Py_ssize_t lenargs = PyTuple_GET_SIZE(args);
  2103. if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
  2104. return -1;
  2105. if (lenargs >= 1) {
  2106. Py_XSETREF(self->msg, Py_NewRef(PyTuple_GET_ITEM(args, 0)));
  2107. }
  2108. if (lenargs == 2) {
  2109. info = PyTuple_GET_ITEM(args, 1);
  2110. info = PySequence_Tuple(info);
  2111. if (!info) {
  2112. return -1;
  2113. }
  2114. self->end_lineno = NULL;
  2115. self->end_offset = NULL;
  2116. if (!PyArg_ParseTuple(info, "OOOO|OO",
  2117. &self->filename, &self->lineno,
  2118. &self->offset, &self->text,
  2119. &self->end_lineno, &self->end_offset)) {
  2120. Py_DECREF(info);
  2121. return -1;
  2122. }
  2123. Py_INCREF(self->filename);
  2124. Py_INCREF(self->lineno);
  2125. Py_INCREF(self->offset);
  2126. Py_INCREF(self->text);
  2127. Py_XINCREF(self->end_lineno);
  2128. Py_XINCREF(self->end_offset);
  2129. Py_DECREF(info);
  2130. if (self->end_lineno != NULL && self->end_offset == NULL) {
  2131. PyErr_SetString(PyExc_TypeError, "end_offset must be provided when end_lineno is provided");
  2132. return -1;
  2133. }
  2134. }
  2135. return 0;
  2136. }
  2137. static int
  2138. SyntaxError_clear(PySyntaxErrorObject *self)
  2139. {
  2140. Py_CLEAR(self->msg);
  2141. Py_CLEAR(self->filename);
  2142. Py_CLEAR(self->lineno);
  2143. Py_CLEAR(self->offset);
  2144. Py_CLEAR(self->end_lineno);
  2145. Py_CLEAR(self->end_offset);
  2146. Py_CLEAR(self->text);
  2147. Py_CLEAR(self->print_file_and_line);
  2148. return BaseException_clear((PyBaseExceptionObject *)self);
  2149. }
  2150. static void
  2151. SyntaxError_dealloc(PySyntaxErrorObject *self)
  2152. {
  2153. _PyObject_GC_UNTRACK(self);
  2154. SyntaxError_clear(self);
  2155. Py_TYPE(self)->tp_free((PyObject *)self);
  2156. }
  2157. static int
  2158. SyntaxError_traverse(PySyntaxErrorObject *self, visitproc visit, void *arg)
  2159. {
  2160. Py_VISIT(self->msg);
  2161. Py_VISIT(self->filename);
  2162. Py_VISIT(self->lineno);
  2163. Py_VISIT(self->offset);
  2164. Py_VISIT(self->end_lineno);
  2165. Py_VISIT(self->end_offset);
  2166. Py_VISIT(self->text);
  2167. Py_VISIT(self->print_file_and_line);
  2168. return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
  2169. }
  2170. /* This is called "my_basename" instead of just "basename" to avoid name
  2171. conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
  2172. defined, and Python does define that. */
  2173. static PyObject*
  2174. my_basename(PyObject *name)
  2175. {
  2176. Py_ssize_t i, size, offset;
  2177. int kind;
  2178. const void *data;
  2179. if (PyUnicode_READY(name))
  2180. return NULL;
  2181. kind = PyUnicode_KIND(name);
  2182. data = PyUnicode_DATA(name);
  2183. size = PyUnicode_GET_LENGTH(name);
  2184. offset = 0;
  2185. for(i=0; i < size; i++) {
  2186. if (PyUnicode_READ(kind, data, i) == SEP) {
  2187. offset = i + 1;
  2188. }
  2189. }
  2190. if (offset != 0) {
  2191. return PyUnicode_Substring(name, offset, size);
  2192. }
  2193. else {
  2194. return Py_NewRef(name);
  2195. }
  2196. }
  2197. static PyObject *
  2198. SyntaxError_str(PySyntaxErrorObject *self)
  2199. {
  2200. int have_lineno = 0;
  2201. PyObject *filename;
  2202. PyObject *result;
  2203. /* Below, we always ignore overflow errors, just printing -1.
  2204. Still, we cannot allow an OverflowError to be raised, so
  2205. we need to call PyLong_AsLongAndOverflow. */
  2206. int overflow;
  2207. /* XXX -- do all the additional formatting with filename and
  2208. lineno here */
  2209. if (self->filename && PyUnicode_Check(self->filename)) {
  2210. filename = my_basename(self->filename);
  2211. if (filename == NULL)
  2212. return NULL;
  2213. } else {
  2214. filename = NULL;
  2215. }
  2216. have_lineno = (self->lineno != NULL) && PyLong_CheckExact(self->lineno);
  2217. if (!filename && !have_lineno)
  2218. return PyObject_Str(self->msg ? self->msg : Py_None);
  2219. if (filename && have_lineno)
  2220. result = PyUnicode_FromFormat("%S (%U, line %ld)",
  2221. self->msg ? self->msg : Py_None,
  2222. filename,
  2223. PyLong_AsLongAndOverflow(self->lineno, &overflow));
  2224. else if (filename)
  2225. result = PyUnicode_FromFormat("%S (%U)",
  2226. self->msg ? self->msg : Py_None,
  2227. filename);
  2228. else /* only have_lineno */
  2229. result = PyUnicode_FromFormat("%S (line %ld)",
  2230. self->msg ? self->msg : Py_None,
  2231. PyLong_AsLongAndOverflow(self->lineno, &overflow));
  2232. Py_XDECREF(filename);
  2233. return result;
  2234. }
  2235. static PyMemberDef SyntaxError_members[] = {
  2236. {"msg", T_OBJECT, offsetof(PySyntaxErrorObject, msg), 0,
  2237. PyDoc_STR("exception msg")},
  2238. {"filename", T_OBJECT, offsetof(PySyntaxErrorObject, filename), 0,
  2239. PyDoc_STR("exception filename")},
  2240. {"lineno", T_OBJECT, offsetof(PySyntaxErrorObject, lineno), 0,
  2241. PyDoc_STR("exception lineno")},
  2242. {"offset", T_OBJECT, offsetof(PySyntaxErrorObject, offset), 0,
  2243. PyDoc_STR("exception offset")},
  2244. {"text", T_OBJECT, offsetof(PySyntaxErrorObject, text), 0,
  2245. PyDoc_STR("exception text")},
  2246. {"end_lineno", T_OBJECT, offsetof(PySyntaxErrorObject, end_lineno), 0,
  2247. PyDoc_STR("exception end lineno")},
  2248. {"end_offset", T_OBJECT, offsetof(PySyntaxErrorObject, end_offset), 0,
  2249. PyDoc_STR("exception end offset")},
  2250. {"print_file_and_line", T_OBJECT,
  2251. offsetof(PySyntaxErrorObject, print_file_and_line), 0,
  2252. PyDoc_STR("exception print_file_and_line")},
  2253. {NULL} /* Sentinel */
  2254. };
  2255. ComplexExtendsException(PyExc_Exception, SyntaxError, SyntaxError,
  2256. 0, 0, SyntaxError_members, 0,
  2257. SyntaxError_str, "Invalid syntax.");
  2258. /*
  2259. * IndentationError extends SyntaxError
  2260. */
  2261. MiddlingExtendsException(PyExc_SyntaxError, IndentationError, SyntaxError,
  2262. "Improper indentation.");
  2263. /*
  2264. * TabError extends IndentationError
  2265. */
  2266. MiddlingExtendsException(PyExc_IndentationError, TabError, SyntaxError,
  2267. "Improper mixture of spaces and tabs.");
  2268. /*
  2269. * LookupError extends Exception
  2270. */
  2271. SimpleExtendsException(PyExc_Exception, LookupError,
  2272. "Base class for lookup errors.");
  2273. /*
  2274. * IndexError extends LookupError
  2275. */
  2276. SimpleExtendsException(PyExc_LookupError, IndexError,
  2277. "Sequence index out of range.");
  2278. /*
  2279. * KeyError extends LookupError
  2280. */
  2281. static PyObject *
  2282. KeyError_str(PyBaseExceptionObject *self)
  2283. {
  2284. /* If args is a tuple of exactly one item, apply repr to args[0].
  2285. This is done so that e.g. the exception raised by {}[''] prints
  2286. KeyError: ''
  2287. rather than the confusing
  2288. KeyError
  2289. alone. The downside is that if KeyError is raised with an explanatory
  2290. string, that string will be displayed in quotes. Too bad.
  2291. If args is anything else, use the default BaseException__str__().
  2292. */
  2293. if (PyTuple_GET_SIZE(self->args) == 1) {
  2294. return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0));
  2295. }
  2296. return BaseException_str(self);
  2297. }
  2298. ComplexExtendsException(PyExc_LookupError, KeyError, BaseException,
  2299. 0, 0, 0, 0, KeyError_str, "Mapping key not found.");
  2300. /*
  2301. * ValueError extends Exception
  2302. */
  2303. SimpleExtendsException(PyExc_Exception, ValueError,
  2304. "Inappropriate argument value (of correct type).");
  2305. /*
  2306. * UnicodeError extends ValueError
  2307. */
  2308. SimpleExtendsException(PyExc_ValueError, UnicodeError,
  2309. "Unicode related error.");
  2310. static PyObject *
  2311. get_string(PyObject *attr, const char *name)
  2312. {
  2313. if (!attr) {
  2314. PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
  2315. return NULL;
  2316. }
  2317. if (!PyBytes_Check(attr)) {
  2318. PyErr_Format(PyExc_TypeError, "%.200s attribute must be bytes", name);
  2319. return NULL;
  2320. }
  2321. return Py_NewRef(attr);
  2322. }
  2323. static PyObject *
  2324. get_unicode(PyObject *attr, const char *name)
  2325. {
  2326. if (!attr) {
  2327. PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
  2328. return NULL;
  2329. }
  2330. if (!PyUnicode_Check(attr)) {
  2331. PyErr_Format(PyExc_TypeError,
  2332. "%.200s attribute must be unicode", name);
  2333. return NULL;
  2334. }
  2335. return Py_NewRef(attr);
  2336. }
  2337. static int
  2338. set_unicodefromstring(PyObject **attr, const char *value)
  2339. {
  2340. PyObject *obj = PyUnicode_FromString(value);
  2341. if (!obj)
  2342. return -1;
  2343. Py_XSETREF(*attr, obj);
  2344. return 0;
  2345. }
  2346. PyObject *
  2347. PyUnicodeEncodeError_GetEncoding(PyObject *exc)
  2348. {
  2349. return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
  2350. }
  2351. PyObject *
  2352. PyUnicodeDecodeError_GetEncoding(PyObject *exc)
  2353. {
  2354. return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
  2355. }
  2356. PyObject *
  2357. PyUnicodeEncodeError_GetObject(PyObject *exc)
  2358. {
  2359. return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
  2360. }
  2361. PyObject *
  2362. PyUnicodeDecodeError_GetObject(PyObject *exc)
  2363. {
  2364. return get_string(((PyUnicodeErrorObject *)exc)->object, "object");
  2365. }
  2366. PyObject *
  2367. PyUnicodeTranslateError_GetObject(PyObject *exc)
  2368. {
  2369. return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
  2370. }
  2371. int
  2372. PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
  2373. {
  2374. Py_ssize_t size;
  2375. PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
  2376. "object");
  2377. if (!obj)
  2378. return -1;
  2379. *start = ((PyUnicodeErrorObject *)exc)->start;
  2380. size = PyUnicode_GET_LENGTH(obj);
  2381. if (*start<0)
  2382. *start = 0; /*XXX check for values <0*/
  2383. if (*start>=size)
  2384. *start = size-1;
  2385. Py_DECREF(obj);
  2386. return 0;
  2387. }
  2388. int
  2389. PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
  2390. {
  2391. Py_ssize_t size;
  2392. PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
  2393. if (!obj)
  2394. return -1;
  2395. size = PyBytes_GET_SIZE(obj);
  2396. *start = ((PyUnicodeErrorObject *)exc)->start;
  2397. if (*start<0)
  2398. *start = 0;
  2399. if (*start>=size)
  2400. *start = size-1;
  2401. Py_DECREF(obj);
  2402. return 0;
  2403. }
  2404. int
  2405. PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
  2406. {
  2407. return PyUnicodeEncodeError_GetStart(exc, start);
  2408. }
  2409. int
  2410. PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
  2411. {
  2412. ((PyUnicodeErrorObject *)exc)->start = start;
  2413. return 0;
  2414. }
  2415. int
  2416. PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
  2417. {
  2418. ((PyUnicodeErrorObject *)exc)->start = start;
  2419. return 0;
  2420. }
  2421. int
  2422. PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
  2423. {
  2424. ((PyUnicodeErrorObject *)exc)->start = start;
  2425. return 0;
  2426. }
  2427. int
  2428. PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
  2429. {
  2430. Py_ssize_t size;
  2431. PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
  2432. "object");
  2433. if (!obj)
  2434. return -1;
  2435. *end = ((PyUnicodeErrorObject *)exc)->end;
  2436. size = PyUnicode_GET_LENGTH(obj);
  2437. if (*end<1)
  2438. *end = 1;
  2439. if (*end>size)
  2440. *end = size;
  2441. Py_DECREF(obj);
  2442. return 0;
  2443. }
  2444. int
  2445. PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
  2446. {
  2447. Py_ssize_t size;
  2448. PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
  2449. if (!obj)
  2450. return -1;
  2451. size = PyBytes_GET_SIZE(obj);
  2452. *end = ((PyUnicodeErrorObject *)exc)->end;
  2453. if (*end<1)
  2454. *end = 1;
  2455. if (*end>size)
  2456. *end = size;
  2457. Py_DECREF(obj);
  2458. return 0;
  2459. }
  2460. int
  2461. PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end)
  2462. {
  2463. return PyUnicodeEncodeError_GetEnd(exc, end);
  2464. }
  2465. int
  2466. PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
  2467. {
  2468. ((PyUnicodeErrorObject *)exc)->end = end;
  2469. return 0;
  2470. }
  2471. int
  2472. PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
  2473. {
  2474. ((PyUnicodeErrorObject *)exc)->end = end;
  2475. return 0;
  2476. }
  2477. int
  2478. PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
  2479. {
  2480. ((PyUnicodeErrorObject *)exc)->end = end;
  2481. return 0;
  2482. }
  2483. PyObject *
  2484. PyUnicodeEncodeError_GetReason(PyObject *exc)
  2485. {
  2486. return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
  2487. }
  2488. PyObject *
  2489. PyUnicodeDecodeError_GetReason(PyObject *exc)
  2490. {
  2491. return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
  2492. }
  2493. PyObject *
  2494. PyUnicodeTranslateError_GetReason(PyObject *exc)
  2495. {
  2496. return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
  2497. }
  2498. int
  2499. PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
  2500. {
  2501. return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
  2502. reason);
  2503. }
  2504. int
  2505. PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
  2506. {
  2507. return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
  2508. reason);
  2509. }
  2510. int
  2511. PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
  2512. {
  2513. return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
  2514. reason);
  2515. }
  2516. static int
  2517. UnicodeError_clear(PyUnicodeErrorObject *self)
  2518. {
  2519. Py_CLEAR(self->encoding);
  2520. Py_CLEAR(self->object);
  2521. Py_CLEAR(self->reason);
  2522. return BaseException_clear((PyBaseExceptionObject *)self);
  2523. }
  2524. static void
  2525. UnicodeError_dealloc(PyUnicodeErrorObject *self)
  2526. {
  2527. _PyObject_GC_UNTRACK(self);
  2528. UnicodeError_clear(self);
  2529. Py_TYPE(self)->tp_free((PyObject *)self);
  2530. }
  2531. static int
  2532. UnicodeError_traverse(PyUnicodeErrorObject *self, visitproc visit, void *arg)
  2533. {
  2534. Py_VISIT(self->encoding);
  2535. Py_VISIT(self->object);
  2536. Py_VISIT(self->reason);
  2537. return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
  2538. }
  2539. static PyMemberDef UnicodeError_members[] = {
  2540. {"encoding", T_OBJECT, offsetof(PyUnicodeErrorObject, encoding), 0,
  2541. PyDoc_STR("exception encoding")},
  2542. {"object", T_OBJECT, offsetof(PyUnicodeErrorObject, object), 0,
  2543. PyDoc_STR("exception object")},
  2544. {"start", T_PYSSIZET, offsetof(PyUnicodeErrorObject, start), 0,
  2545. PyDoc_STR("exception start")},
  2546. {"end", T_PYSSIZET, offsetof(PyUnicodeErrorObject, end), 0,
  2547. PyDoc_STR("exception end")},
  2548. {"reason", T_OBJECT, offsetof(PyUnicodeErrorObject, reason), 0,
  2549. PyDoc_STR("exception reason")},
  2550. {NULL} /* Sentinel */
  2551. };
  2552. /*
  2553. * UnicodeEncodeError extends UnicodeError
  2554. */
  2555. static int
  2556. UnicodeEncodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
  2557. {
  2558. PyUnicodeErrorObject *err;
  2559. if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
  2560. return -1;
  2561. err = (PyUnicodeErrorObject *)self;
  2562. Py_CLEAR(err->encoding);
  2563. Py_CLEAR(err->object);
  2564. Py_CLEAR(err->reason);
  2565. if (!PyArg_ParseTuple(args, "UUnnU",
  2566. &err->encoding, &err->object,
  2567. &err->start, &err->end, &err->reason)) {
  2568. err->encoding = err->object = err->reason = NULL;
  2569. return -1;
  2570. }
  2571. Py_INCREF(err->encoding);
  2572. Py_INCREF(err->object);
  2573. Py_INCREF(err->reason);
  2574. return 0;
  2575. }
  2576. static PyObject *
  2577. UnicodeEncodeError_str(PyObject *self)
  2578. {
  2579. PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
  2580. PyObject *result = NULL;
  2581. PyObject *reason_str = NULL;
  2582. PyObject *encoding_str = NULL;
  2583. if (!uself->object)
  2584. /* Not properly initialized. */
  2585. return PyUnicode_FromString("");
  2586. /* Get reason and encoding as strings, which they might not be if
  2587. they've been modified after we were constructed. */
  2588. reason_str = PyObject_Str(uself->reason);
  2589. if (reason_str == NULL)
  2590. goto done;
  2591. encoding_str = PyObject_Str(uself->encoding);
  2592. if (encoding_str == NULL)
  2593. goto done;
  2594. if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
  2595. Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
  2596. const char *fmt;
  2597. if (badchar <= 0xff)
  2598. fmt = "'%U' codec can't encode character '\\x%02x' in position %zd: %U";
  2599. else if (badchar <= 0xffff)
  2600. fmt = "'%U' codec can't encode character '\\u%04x' in position %zd: %U";
  2601. else
  2602. fmt = "'%U' codec can't encode character '\\U%08x' in position %zd: %U";
  2603. result = PyUnicode_FromFormat(
  2604. fmt,
  2605. encoding_str,
  2606. (int)badchar,
  2607. uself->start,
  2608. reason_str);
  2609. }
  2610. else {
  2611. result = PyUnicode_FromFormat(
  2612. "'%U' codec can't encode characters in position %zd-%zd: %U",
  2613. encoding_str,
  2614. uself->start,
  2615. uself->end-1,
  2616. reason_str);
  2617. }
  2618. done:
  2619. Py_XDECREF(reason_str);
  2620. Py_XDECREF(encoding_str);
  2621. return result;
  2622. }
  2623. static PyTypeObject _PyExc_UnicodeEncodeError = {
  2624. PyVarObject_HEAD_INIT(NULL, 0)
  2625. "UnicodeEncodeError",
  2626. sizeof(PyUnicodeErrorObject), 0,
  2627. (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2628. (reprfunc)UnicodeEncodeError_str, 0, 0, 0,
  2629. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
  2630. PyDoc_STR("Unicode encoding error."), (traverseproc)UnicodeError_traverse,
  2631. (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
  2632. 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
  2633. (initproc)UnicodeEncodeError_init, 0, BaseException_new,
  2634. };
  2635. PyObject *PyExc_UnicodeEncodeError = (PyObject *)&_PyExc_UnicodeEncodeError;
  2636. /*
  2637. * UnicodeDecodeError extends UnicodeError
  2638. */
  2639. static int
  2640. UnicodeDecodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
  2641. {
  2642. PyUnicodeErrorObject *ude;
  2643. if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
  2644. return -1;
  2645. ude = (PyUnicodeErrorObject *)self;
  2646. Py_CLEAR(ude->encoding);
  2647. Py_CLEAR(ude->object);
  2648. Py_CLEAR(ude->reason);
  2649. if (!PyArg_ParseTuple(args, "UOnnU",
  2650. &ude->encoding, &ude->object,
  2651. &ude->start, &ude->end, &ude->reason)) {
  2652. ude->encoding = ude->object = ude->reason = NULL;
  2653. return -1;
  2654. }
  2655. Py_INCREF(ude->encoding);
  2656. Py_INCREF(ude->object);
  2657. Py_INCREF(ude->reason);
  2658. if (!PyBytes_Check(ude->object)) {
  2659. Py_buffer view;
  2660. if (PyObject_GetBuffer(ude->object, &view, PyBUF_SIMPLE) != 0)
  2661. goto error;
  2662. Py_XSETREF(ude->object, PyBytes_FromStringAndSize(view.buf, view.len));
  2663. PyBuffer_Release(&view);
  2664. if (!ude->object)
  2665. goto error;
  2666. }
  2667. return 0;
  2668. error:
  2669. Py_CLEAR(ude->encoding);
  2670. Py_CLEAR(ude->object);
  2671. Py_CLEAR(ude->reason);
  2672. return -1;
  2673. }
  2674. static PyObject *
  2675. UnicodeDecodeError_str(PyObject *self)
  2676. {
  2677. PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
  2678. PyObject *result = NULL;
  2679. PyObject *reason_str = NULL;
  2680. PyObject *encoding_str = NULL;
  2681. if (!uself->object)
  2682. /* Not properly initialized. */
  2683. return PyUnicode_FromString("");
  2684. /* Get reason and encoding as strings, which they might not be if
  2685. they've been modified after we were constructed. */
  2686. reason_str = PyObject_Str(uself->reason);
  2687. if (reason_str == NULL)
  2688. goto done;
  2689. encoding_str = PyObject_Str(uself->encoding);
  2690. if (encoding_str == NULL)
  2691. goto done;
  2692. if (uself->start < PyBytes_GET_SIZE(uself->object) && uself->end == uself->start+1) {
  2693. int byte = (int)(PyBytes_AS_STRING(((PyUnicodeErrorObject *)self)->object)[uself->start]&0xff);
  2694. result = PyUnicode_FromFormat(
  2695. "'%U' codec can't decode byte 0x%02x in position %zd: %U",
  2696. encoding_str,
  2697. byte,
  2698. uself->start,
  2699. reason_str);
  2700. }
  2701. else {
  2702. result = PyUnicode_FromFormat(
  2703. "'%U' codec can't decode bytes in position %zd-%zd: %U",
  2704. encoding_str,
  2705. uself->start,
  2706. uself->end-1,
  2707. reason_str
  2708. );
  2709. }
  2710. done:
  2711. Py_XDECREF(reason_str);
  2712. Py_XDECREF(encoding_str);
  2713. return result;
  2714. }
  2715. static PyTypeObject _PyExc_UnicodeDecodeError = {
  2716. PyVarObject_HEAD_INIT(NULL, 0)
  2717. "UnicodeDecodeError",
  2718. sizeof(PyUnicodeErrorObject), 0,
  2719. (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2720. (reprfunc)UnicodeDecodeError_str, 0, 0, 0,
  2721. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
  2722. PyDoc_STR("Unicode decoding error."), (traverseproc)UnicodeError_traverse,
  2723. (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
  2724. 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
  2725. (initproc)UnicodeDecodeError_init, 0, BaseException_new,
  2726. };
  2727. PyObject *PyExc_UnicodeDecodeError = (PyObject *)&_PyExc_UnicodeDecodeError;
  2728. PyObject *
  2729. PyUnicodeDecodeError_Create(
  2730. const char *encoding, const char *object, Py_ssize_t length,
  2731. Py_ssize_t start, Py_ssize_t end, const char *reason)
  2732. {
  2733. return PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
  2734. encoding, object, length, start, end, reason);
  2735. }
  2736. /*
  2737. * UnicodeTranslateError extends UnicodeError
  2738. */
  2739. static int
  2740. UnicodeTranslateError_init(PyUnicodeErrorObject *self, PyObject *args,
  2741. PyObject *kwds)
  2742. {
  2743. if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
  2744. return -1;
  2745. Py_CLEAR(self->object);
  2746. Py_CLEAR(self->reason);
  2747. if (!PyArg_ParseTuple(args, "UnnU",
  2748. &self->object,
  2749. &self->start, &self->end, &self->reason)) {
  2750. self->object = self->reason = NULL;
  2751. return -1;
  2752. }
  2753. Py_INCREF(self->object);
  2754. Py_INCREF(self->reason);
  2755. return 0;
  2756. }
  2757. static PyObject *
  2758. UnicodeTranslateError_str(PyObject *self)
  2759. {
  2760. PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
  2761. PyObject *result = NULL;
  2762. PyObject *reason_str = NULL;
  2763. if (!uself->object)
  2764. /* Not properly initialized. */
  2765. return PyUnicode_FromString("");
  2766. /* Get reason as a string, which it might not be if it's been
  2767. modified after we were constructed. */
  2768. reason_str = PyObject_Str(uself->reason);
  2769. if (reason_str == NULL)
  2770. goto done;
  2771. if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
  2772. Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
  2773. const char *fmt;
  2774. if (badchar <= 0xff)
  2775. fmt = "can't translate character '\\x%02x' in position %zd: %U";
  2776. else if (badchar <= 0xffff)
  2777. fmt = "can't translate character '\\u%04x' in position %zd: %U";
  2778. else
  2779. fmt = "can't translate character '\\U%08x' in position %zd: %U";
  2780. result = PyUnicode_FromFormat(
  2781. fmt,
  2782. (int)badchar,
  2783. uself->start,
  2784. reason_str
  2785. );
  2786. } else {
  2787. result = PyUnicode_FromFormat(
  2788. "can't translate characters in position %zd-%zd: %U",
  2789. uself->start,
  2790. uself->end-1,
  2791. reason_str
  2792. );
  2793. }
  2794. done:
  2795. Py_XDECREF(reason_str);
  2796. return result;
  2797. }
  2798. static PyTypeObject _PyExc_UnicodeTranslateError = {
  2799. PyVarObject_HEAD_INIT(NULL, 0)
  2800. "UnicodeTranslateError",
  2801. sizeof(PyUnicodeErrorObject), 0,
  2802. (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2803. (reprfunc)UnicodeTranslateError_str, 0, 0, 0,
  2804. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
  2805. PyDoc_STR("Unicode translation error."), (traverseproc)UnicodeError_traverse,
  2806. (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
  2807. 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
  2808. (initproc)UnicodeTranslateError_init, 0, BaseException_new,
  2809. };
  2810. PyObject *PyExc_UnicodeTranslateError = (PyObject *)&_PyExc_UnicodeTranslateError;
  2811. PyObject *
  2812. _PyUnicodeTranslateError_Create(
  2813. PyObject *object,
  2814. Py_ssize_t start, Py_ssize_t end, const char *reason)
  2815. {
  2816. return PyObject_CallFunction(PyExc_UnicodeTranslateError, "Onns",
  2817. object, start, end, reason);
  2818. }
  2819. /*
  2820. * AssertionError extends Exception
  2821. */
  2822. SimpleExtendsException(PyExc_Exception, AssertionError,
  2823. "Assertion failed.");
  2824. /*
  2825. * ArithmeticError extends Exception
  2826. */
  2827. SimpleExtendsException(PyExc_Exception, ArithmeticError,
  2828. "Base class for arithmetic errors.");
  2829. /*
  2830. * FloatingPointError extends ArithmeticError
  2831. */
  2832. SimpleExtendsException(PyExc_ArithmeticError, FloatingPointError,
  2833. "Floating-point operation failed.");
  2834. /*
  2835. * OverflowError extends ArithmeticError
  2836. */
  2837. SimpleExtendsException(PyExc_ArithmeticError, OverflowError,
  2838. "Result too large to be represented.");
  2839. /*
  2840. * ZeroDivisionError extends ArithmeticError
  2841. */
  2842. SimpleExtendsException(PyExc_ArithmeticError, ZeroDivisionError,
  2843. "Second argument to a division or modulo operation was zero.");
  2844. /*
  2845. * SystemError extends Exception
  2846. */
  2847. SimpleExtendsException(PyExc_Exception, SystemError,
  2848. "Internal error in the Python interpreter.\n"
  2849. "\n"
  2850. "Please report this to the Python maintainer, along with the traceback,\n"
  2851. "the Python version, and the hardware/OS platform and version.");
  2852. /*
  2853. * ReferenceError extends Exception
  2854. */
  2855. SimpleExtendsException(PyExc_Exception, ReferenceError,
  2856. "Weak ref proxy used after referent went away.");
  2857. /*
  2858. * MemoryError extends Exception
  2859. */
  2860. #define MEMERRORS_SAVE 16
  2861. static PyObject *
  2862. get_memory_error(int allow_allocation, PyObject *args, PyObject *kwds)
  2863. {
  2864. PyBaseExceptionObject *self;
  2865. struct _Py_exc_state *state = get_exc_state();
  2866. if (state->memerrors_freelist == NULL) {
  2867. if (!allow_allocation) {
  2868. PyInterpreterState *interp = _PyInterpreterState_GET();
  2869. return Py_NewRef(
  2870. &_Py_INTERP_SINGLETON(interp, last_resort_memory_error));
  2871. }
  2872. PyObject *result = BaseException_new((PyTypeObject *)PyExc_MemoryError, args, kwds);
  2873. return result;
  2874. }
  2875. /* Fetch object from freelist and revive it */
  2876. self = state->memerrors_freelist;
  2877. self->args = PyTuple_New(0);
  2878. /* This shouldn't happen since the empty tuple is persistent */
  2879. if (self->args == NULL) {
  2880. return NULL;
  2881. }
  2882. state->memerrors_freelist = (PyBaseExceptionObject *) self->dict;
  2883. state->memerrors_numfree--;
  2884. self->dict = NULL;
  2885. _Py_NewReference((PyObject *)self);
  2886. _PyObject_GC_TRACK(self);
  2887. return (PyObject *)self;
  2888. }
  2889. static PyObject *
  2890. MemoryError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  2891. {
  2892. /* If this is a subclass of MemoryError, don't use the freelist
  2893. * and just return a fresh object */
  2894. if (type != (PyTypeObject *) PyExc_MemoryError) {
  2895. return BaseException_new(type, args, kwds);
  2896. }
  2897. return get_memory_error(1, args, kwds);
  2898. }
  2899. PyObject *
  2900. _PyErr_NoMemory(PyThreadState *tstate)
  2901. {
  2902. if (Py_IS_TYPE(PyExc_MemoryError, NULL)) {
  2903. /* PyErr_NoMemory() has been called before PyExc_MemoryError has been
  2904. initialized by _PyExc_Init() */
  2905. Py_FatalError("Out of memory and PyExc_MemoryError is not "
  2906. "initialized yet");
  2907. }
  2908. PyObject *err = get_memory_error(0, NULL, NULL);
  2909. if (err != NULL) {
  2910. _PyErr_SetRaisedException(tstate, err);
  2911. }
  2912. return NULL;
  2913. }
  2914. static void
  2915. MemoryError_dealloc(PyBaseExceptionObject *self)
  2916. {
  2917. _PyObject_GC_UNTRACK(self);
  2918. BaseException_clear(self);
  2919. /* If this is a subclass of MemoryError, we don't need to
  2920. * do anything in the free-list*/
  2921. if (!Py_IS_TYPE(self, (PyTypeObject *) PyExc_MemoryError)) {
  2922. Py_TYPE(self)->tp_free((PyObject *)self);
  2923. return;
  2924. }
  2925. struct _Py_exc_state *state = get_exc_state();
  2926. if (state->memerrors_numfree >= MEMERRORS_SAVE) {
  2927. Py_TYPE(self)->tp_free((PyObject *)self);
  2928. }
  2929. else {
  2930. self->dict = (PyObject *) state->memerrors_freelist;
  2931. state->memerrors_freelist = self;
  2932. state->memerrors_numfree++;
  2933. }
  2934. }
  2935. static int
  2936. preallocate_memerrors(void)
  2937. {
  2938. /* We create enough MemoryErrors and then decref them, which will fill
  2939. up the freelist. */
  2940. int i;
  2941. PyObject *errors[MEMERRORS_SAVE];
  2942. for (i = 0; i < MEMERRORS_SAVE; i++) {
  2943. errors[i] = MemoryError_new((PyTypeObject *) PyExc_MemoryError,
  2944. NULL, NULL);
  2945. if (!errors[i]) {
  2946. return -1;
  2947. }
  2948. }
  2949. for (i = 0; i < MEMERRORS_SAVE; i++) {
  2950. Py_DECREF(errors[i]);
  2951. }
  2952. return 0;
  2953. }
  2954. static void
  2955. free_preallocated_memerrors(struct _Py_exc_state *state)
  2956. {
  2957. while (state->memerrors_freelist != NULL) {
  2958. PyObject *self = (PyObject *) state->memerrors_freelist;
  2959. state->memerrors_freelist = (PyBaseExceptionObject *)state->memerrors_freelist->dict;
  2960. Py_TYPE(self)->tp_free((PyObject *)self);
  2961. }
  2962. }
  2963. PyTypeObject _PyExc_MemoryError = {
  2964. PyVarObject_HEAD_INIT(NULL, 0)
  2965. "MemoryError",
  2966. sizeof(PyBaseExceptionObject),
  2967. 0, (destructor)MemoryError_dealloc, 0, 0, 0, 0, 0, 0, 0,
  2968. 0, 0, 0, 0, 0, 0, 0,
  2969. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
  2970. PyDoc_STR("Out of memory."), (traverseproc)BaseException_traverse,
  2971. (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_PyExc_Exception,
  2972. 0, 0, 0, offsetof(PyBaseExceptionObject, dict),
  2973. (initproc)BaseException_init, 0, MemoryError_new
  2974. };
  2975. PyObject *PyExc_MemoryError = (PyObject *) &_PyExc_MemoryError;
  2976. /*
  2977. * BufferError extends Exception
  2978. */
  2979. SimpleExtendsException(PyExc_Exception, BufferError, "Buffer error.");
  2980. /* Warning category docstrings */
  2981. /*
  2982. * Warning extends Exception
  2983. */
  2984. SimpleExtendsException(PyExc_Exception, Warning,
  2985. "Base class for warning categories.");
  2986. /*
  2987. * UserWarning extends Warning
  2988. */
  2989. SimpleExtendsException(PyExc_Warning, UserWarning,
  2990. "Base class for warnings generated by user code.");
  2991. /*
  2992. * DeprecationWarning extends Warning
  2993. */
  2994. SimpleExtendsException(PyExc_Warning, DeprecationWarning,
  2995. "Base class for warnings about deprecated features.");
  2996. /*
  2997. * PendingDeprecationWarning extends Warning
  2998. */
  2999. SimpleExtendsException(PyExc_Warning, PendingDeprecationWarning,
  3000. "Base class for warnings about features which will be deprecated\n"
  3001. "in the future.");
  3002. /*
  3003. * SyntaxWarning extends Warning
  3004. */
  3005. SimpleExtendsException(PyExc_Warning, SyntaxWarning,
  3006. "Base class for warnings about dubious syntax.");
  3007. /*
  3008. * RuntimeWarning extends Warning
  3009. */
  3010. SimpleExtendsException(PyExc_Warning, RuntimeWarning,
  3011. "Base class for warnings about dubious runtime behavior.");
  3012. /*
  3013. * FutureWarning extends Warning
  3014. */
  3015. SimpleExtendsException(PyExc_Warning, FutureWarning,
  3016. "Base class for warnings about constructs that will change semantically\n"
  3017. "in the future.");
  3018. /*
  3019. * ImportWarning extends Warning
  3020. */
  3021. SimpleExtendsException(PyExc_Warning, ImportWarning,
  3022. "Base class for warnings about probable mistakes in module imports");
  3023. /*
  3024. * UnicodeWarning extends Warning
  3025. */
  3026. SimpleExtendsException(PyExc_Warning, UnicodeWarning,
  3027. "Base class for warnings about Unicode related problems, mostly\n"
  3028. "related to conversion problems.");
  3029. /*
  3030. * BytesWarning extends Warning
  3031. */
  3032. SimpleExtendsException(PyExc_Warning, BytesWarning,
  3033. "Base class for warnings about bytes and buffer related problems, mostly\n"
  3034. "related to conversion from str or comparing to str.");
  3035. /*
  3036. * EncodingWarning extends Warning
  3037. */
  3038. SimpleExtendsException(PyExc_Warning, EncodingWarning,
  3039. "Base class for warnings about encodings.");
  3040. /*
  3041. * ResourceWarning extends Warning
  3042. */
  3043. SimpleExtendsException(PyExc_Warning, ResourceWarning,
  3044. "Base class for warnings about resource usage.");
  3045. #ifdef MS_WINDOWS
  3046. #include <winsock2.h>
  3047. /* The following constants were added to errno.h in VS2010 but have
  3048. preferred WSA equivalents. */
  3049. #undef EADDRINUSE
  3050. #undef EADDRNOTAVAIL
  3051. #undef EAFNOSUPPORT
  3052. #undef EALREADY
  3053. #undef ECONNABORTED
  3054. #undef ECONNREFUSED
  3055. #undef ECONNRESET
  3056. #undef EDESTADDRREQ
  3057. #undef EHOSTUNREACH
  3058. #undef EINPROGRESS
  3059. #undef EISCONN
  3060. #undef ELOOP
  3061. #undef EMSGSIZE
  3062. #undef ENETDOWN
  3063. #undef ENETRESET
  3064. #undef ENETUNREACH
  3065. #undef ENOBUFS
  3066. #undef ENOPROTOOPT
  3067. #undef ENOTCONN
  3068. #undef ENOTSOCK
  3069. #undef EOPNOTSUPP
  3070. #undef EPROTONOSUPPORT
  3071. #undef EPROTOTYPE
  3072. #undef ETIMEDOUT
  3073. #undef EWOULDBLOCK
  3074. #if defined(WSAEALREADY) && !defined(EALREADY)
  3075. #define EALREADY WSAEALREADY
  3076. #endif
  3077. #if defined(WSAECONNABORTED) && !defined(ECONNABORTED)
  3078. #define ECONNABORTED WSAECONNABORTED
  3079. #endif
  3080. #if defined(WSAECONNREFUSED) && !defined(ECONNREFUSED)
  3081. #define ECONNREFUSED WSAECONNREFUSED
  3082. #endif
  3083. #if defined(WSAECONNRESET) && !defined(ECONNRESET)
  3084. #define ECONNRESET WSAECONNRESET
  3085. #endif
  3086. #if defined(WSAEINPROGRESS) && !defined(EINPROGRESS)
  3087. #define EINPROGRESS WSAEINPROGRESS
  3088. #endif
  3089. #if defined(WSAESHUTDOWN) && !defined(ESHUTDOWN)
  3090. #define ESHUTDOWN WSAESHUTDOWN
  3091. #endif
  3092. #if defined(WSAETIMEDOUT) && !defined(ETIMEDOUT)
  3093. #define ETIMEDOUT WSAETIMEDOUT
  3094. #endif
  3095. #if defined(WSAEWOULDBLOCK) && !defined(EWOULDBLOCK)
  3096. #define EWOULDBLOCK WSAEWOULDBLOCK
  3097. #endif
  3098. #endif /* MS_WINDOWS */
  3099. struct static_exception {
  3100. PyTypeObject *exc;
  3101. const char *name;
  3102. };
  3103. static struct static_exception static_exceptions[] = {
  3104. #define ITEM(NAME) {&_PyExc_##NAME, #NAME}
  3105. // Level 1
  3106. ITEM(BaseException),
  3107. // Level 2: BaseException subclasses
  3108. ITEM(BaseExceptionGroup),
  3109. ITEM(Exception),
  3110. ITEM(GeneratorExit),
  3111. ITEM(KeyboardInterrupt),
  3112. ITEM(SystemExit),
  3113. // Level 3: Exception(BaseException) subclasses
  3114. ITEM(ArithmeticError),
  3115. ITEM(AssertionError),
  3116. ITEM(AttributeError),
  3117. ITEM(BufferError),
  3118. ITEM(EOFError),
  3119. //ITEM(ExceptionGroup),
  3120. ITEM(ImportError),
  3121. ITEM(LookupError),
  3122. ITEM(MemoryError),
  3123. ITEM(NameError),
  3124. ITEM(OSError),
  3125. ITEM(ReferenceError),
  3126. ITEM(RuntimeError),
  3127. ITEM(StopAsyncIteration),
  3128. ITEM(StopIteration),
  3129. ITEM(SyntaxError),
  3130. ITEM(SystemError),
  3131. ITEM(TypeError),
  3132. ITEM(ValueError),
  3133. ITEM(Warning),
  3134. // Level 4: ArithmeticError(Exception) subclasses
  3135. ITEM(FloatingPointError),
  3136. ITEM(OverflowError),
  3137. ITEM(ZeroDivisionError),
  3138. // Level 4: Warning(Exception) subclasses
  3139. ITEM(BytesWarning),
  3140. ITEM(DeprecationWarning),
  3141. ITEM(EncodingWarning),
  3142. ITEM(FutureWarning),
  3143. ITEM(ImportWarning),
  3144. ITEM(PendingDeprecationWarning),
  3145. ITEM(ResourceWarning),
  3146. ITEM(RuntimeWarning),
  3147. ITEM(SyntaxWarning),
  3148. ITEM(UnicodeWarning),
  3149. ITEM(UserWarning),
  3150. // Level 4: OSError(Exception) subclasses
  3151. ITEM(BlockingIOError),
  3152. ITEM(ChildProcessError),
  3153. ITEM(ConnectionError),
  3154. ITEM(FileExistsError),
  3155. ITEM(FileNotFoundError),
  3156. ITEM(InterruptedError),
  3157. ITEM(IsADirectoryError),
  3158. ITEM(NotADirectoryError),
  3159. ITEM(PermissionError),
  3160. ITEM(ProcessLookupError),
  3161. ITEM(TimeoutError),
  3162. // Level 4: Other subclasses
  3163. ITEM(IndentationError), // base: SyntaxError(Exception)
  3164. ITEM(IndexError), // base: LookupError(Exception)
  3165. ITEM(KeyError), // base: LookupError(Exception)
  3166. ITEM(ModuleNotFoundError), // base: ImportError(Exception)
  3167. ITEM(NotImplementedError), // base: RuntimeError(Exception)
  3168. ITEM(RecursionError), // base: RuntimeError(Exception)
  3169. ITEM(UnboundLocalError), // base: NameError(Exception)
  3170. ITEM(UnicodeError), // base: ValueError(Exception)
  3171. // Level 5: ConnectionError(OSError) subclasses
  3172. ITEM(BrokenPipeError),
  3173. ITEM(ConnectionAbortedError),
  3174. ITEM(ConnectionRefusedError),
  3175. ITEM(ConnectionResetError),
  3176. // Level 5: IndentationError(SyntaxError) subclasses
  3177. ITEM(TabError), // base: IndentationError
  3178. // Level 5: UnicodeError(ValueError) subclasses
  3179. ITEM(UnicodeDecodeError),
  3180. ITEM(UnicodeEncodeError),
  3181. ITEM(UnicodeTranslateError),
  3182. #undef ITEM
  3183. };
  3184. int
  3185. _PyExc_InitTypes(PyInterpreterState *interp)
  3186. {
  3187. for (size_t i=0; i < Py_ARRAY_LENGTH(static_exceptions); i++) {
  3188. PyTypeObject *exc = static_exceptions[i].exc;
  3189. if (_PyStaticType_InitBuiltin(interp, exc) < 0) {
  3190. return -1;
  3191. }
  3192. }
  3193. return 0;
  3194. }
  3195. static void
  3196. _PyExc_FiniTypes(PyInterpreterState *interp)
  3197. {
  3198. for (Py_ssize_t i=Py_ARRAY_LENGTH(static_exceptions) - 1; i >= 0; i--) {
  3199. PyTypeObject *exc = static_exceptions[i].exc;
  3200. _PyStaticType_Dealloc(interp, exc);
  3201. }
  3202. }
  3203. PyStatus
  3204. _PyExc_InitGlobalObjects(PyInterpreterState *interp)
  3205. {
  3206. if (preallocate_memerrors() < 0) {
  3207. return _PyStatus_NO_MEMORY();
  3208. }
  3209. return _PyStatus_OK();
  3210. }
  3211. PyStatus
  3212. _PyExc_InitState(PyInterpreterState *interp)
  3213. {
  3214. struct _Py_exc_state *state = &interp->exc_state;
  3215. #define ADD_ERRNO(TYPE, CODE) \
  3216. do { \
  3217. PyObject *_code = PyLong_FromLong(CODE); \
  3218. assert(_PyObject_RealIsSubclass(PyExc_ ## TYPE, PyExc_OSError)); \
  3219. if (!_code || PyDict_SetItem(state->errnomap, _code, PyExc_ ## TYPE)) { \
  3220. Py_XDECREF(_code); \
  3221. return _PyStatus_ERR("errmap insertion problem."); \
  3222. } \
  3223. Py_DECREF(_code); \
  3224. } while (0)
  3225. /* Add exceptions to errnomap */
  3226. assert(state->errnomap == NULL);
  3227. state->errnomap = PyDict_New();
  3228. if (!state->errnomap) {
  3229. return _PyStatus_NO_MEMORY();
  3230. }
  3231. ADD_ERRNO(BlockingIOError, EAGAIN);
  3232. ADD_ERRNO(BlockingIOError, EALREADY);
  3233. ADD_ERRNO(BlockingIOError, EINPROGRESS);
  3234. ADD_ERRNO(BlockingIOError, EWOULDBLOCK);
  3235. ADD_ERRNO(BrokenPipeError, EPIPE);
  3236. #ifdef ESHUTDOWN
  3237. ADD_ERRNO(BrokenPipeError, ESHUTDOWN);
  3238. #endif
  3239. ADD_ERRNO(ChildProcessError, ECHILD);
  3240. ADD_ERRNO(ConnectionAbortedError, ECONNABORTED);
  3241. ADD_ERRNO(ConnectionRefusedError, ECONNREFUSED);
  3242. ADD_ERRNO(ConnectionResetError, ECONNRESET);
  3243. ADD_ERRNO(FileExistsError, EEXIST);
  3244. ADD_ERRNO(FileNotFoundError, ENOENT);
  3245. ADD_ERRNO(IsADirectoryError, EISDIR);
  3246. ADD_ERRNO(NotADirectoryError, ENOTDIR);
  3247. ADD_ERRNO(InterruptedError, EINTR);
  3248. ADD_ERRNO(PermissionError, EACCES);
  3249. ADD_ERRNO(PermissionError, EPERM);
  3250. #ifdef ENOTCAPABLE
  3251. // Extension for WASI capability-based security. Process lacks
  3252. // capability to access a resource.
  3253. ADD_ERRNO(PermissionError, ENOTCAPABLE);
  3254. #endif
  3255. ADD_ERRNO(ProcessLookupError, ESRCH);
  3256. ADD_ERRNO(TimeoutError, ETIMEDOUT);
  3257. return _PyStatus_OK();
  3258. #undef ADD_ERRNO
  3259. }
  3260. /* Add exception types to the builtins module */
  3261. int
  3262. _PyBuiltins_AddExceptions(PyObject *bltinmod)
  3263. {
  3264. PyObject *mod_dict = PyModule_GetDict(bltinmod);
  3265. if (mod_dict == NULL) {
  3266. return -1;
  3267. }
  3268. for (size_t i=0; i < Py_ARRAY_LENGTH(static_exceptions); i++) {
  3269. struct static_exception item = static_exceptions[i];
  3270. if (PyDict_SetItemString(mod_dict, item.name, (PyObject*)item.exc)) {
  3271. return -1;
  3272. }
  3273. }
  3274. PyObject *PyExc_ExceptionGroup = create_exception_group_class();
  3275. if (!PyExc_ExceptionGroup) {
  3276. return -1;
  3277. }
  3278. if (PyDict_SetItemString(mod_dict, "ExceptionGroup", PyExc_ExceptionGroup)) {
  3279. return -1;
  3280. }
  3281. #define INIT_ALIAS(NAME, TYPE) \
  3282. do { \
  3283. PyExc_ ## NAME = PyExc_ ## TYPE; \
  3284. if (PyDict_SetItemString(mod_dict, # NAME, PyExc_ ## TYPE)) { \
  3285. return -1; \
  3286. } \
  3287. } while (0)
  3288. INIT_ALIAS(EnvironmentError, OSError);
  3289. INIT_ALIAS(IOError, OSError);
  3290. #ifdef MS_WINDOWS
  3291. INIT_ALIAS(WindowsError, OSError);
  3292. #endif
  3293. #undef INIT_ALIAS
  3294. return 0;
  3295. }
  3296. void
  3297. _PyExc_ClearExceptionGroupType(PyInterpreterState *interp)
  3298. {
  3299. struct _Py_exc_state *state = &interp->exc_state;
  3300. Py_CLEAR(state->PyExc_ExceptionGroup);
  3301. }
  3302. void
  3303. _PyExc_Fini(PyInterpreterState *interp)
  3304. {
  3305. struct _Py_exc_state *state = &interp->exc_state;
  3306. free_preallocated_memerrors(state);
  3307. Py_CLEAR(state->errnomap);
  3308. _PyExc_FiniTypes(interp);
  3309. }
  3310. int
  3311. _PyException_AddNote(PyObject *exc, PyObject *note)
  3312. {
  3313. if (!PyExceptionInstance_Check(exc)) {
  3314. PyErr_Format(PyExc_TypeError,
  3315. "exc must be an exception, not '%s'",
  3316. Py_TYPE(exc)->tp_name);
  3317. return -1;
  3318. }
  3319. PyObject *r = BaseException_add_note(exc, note);
  3320. int res = r == NULL ? -1 : 0;
  3321. Py_XDECREF(r);
  3322. return res;
  3323. }