errors.c 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990
  1. /* Error handling */
  2. #include "Python.h"
  3. #include "pycore_call.h" // _PyObject_CallNoArgs()
  4. #include "pycore_initconfig.h" // _PyStatus_ERR()
  5. #include "pycore_pyerrors.h" // _PyErr_Format()
  6. #include "pycore_pystate.h" // _PyThreadState_GET()
  7. #include "pycore_structseq.h" // _PyStructSequence_FiniBuiltin()
  8. #include "pycore_sysmodule.h" // _PySys_Audit()
  9. #include "pycore_traceback.h" // _PyTraceBack_FromFrame()
  10. #include <ctype.h>
  11. #ifdef MS_WINDOWS
  12. # include <windows.h>
  13. # include <winbase.h>
  14. # include <stdlib.h> // _sys_nerr
  15. #endif
  16. #ifdef __cplusplus
  17. extern "C" {
  18. #endif
  19. /* Forward declarations */
  20. static PyObject *
  21. _PyErr_FormatV(PyThreadState *tstate, PyObject *exception,
  22. const char *format, va_list vargs);
  23. void
  24. _PyErr_SetRaisedException(PyThreadState *tstate, PyObject *exc)
  25. {
  26. PyObject *old_exc = tstate->current_exception;
  27. tstate->current_exception = exc;
  28. Py_XDECREF(old_exc);
  29. }
  30. static PyObject*
  31. _PyErr_CreateException(PyObject *exception_type, PyObject *value)
  32. {
  33. PyObject *exc;
  34. if (value == NULL || value == Py_None) {
  35. exc = _PyObject_CallNoArgs(exception_type);
  36. }
  37. else if (PyTuple_Check(value)) {
  38. exc = PyObject_Call(exception_type, value, NULL);
  39. }
  40. else {
  41. exc = PyObject_CallOneArg(exception_type, value);
  42. }
  43. if (exc != NULL && !PyExceptionInstance_Check(exc)) {
  44. PyErr_Format(PyExc_TypeError,
  45. "calling %R should have returned an instance of "
  46. "BaseException, not %s",
  47. exception_type, Py_TYPE(exc)->tp_name);
  48. Py_CLEAR(exc);
  49. }
  50. return exc;
  51. }
  52. void
  53. _PyErr_Restore(PyThreadState *tstate, PyObject *type, PyObject *value,
  54. PyObject *traceback)
  55. {
  56. if (type == NULL) {
  57. assert(value == NULL);
  58. assert(traceback == NULL);
  59. _PyErr_SetRaisedException(tstate, NULL);
  60. return;
  61. }
  62. assert(PyExceptionClass_Check(type));
  63. if (value != NULL && type == (PyObject *)Py_TYPE(value)) {
  64. /* Already normalized */
  65. assert(((PyBaseExceptionObject *)value)->traceback != Py_None);
  66. }
  67. else {
  68. PyObject *exc = _PyErr_CreateException(type, value);
  69. Py_XDECREF(value);
  70. if (exc == NULL) {
  71. Py_DECREF(type);
  72. Py_XDECREF(traceback);
  73. return;
  74. }
  75. value = exc;
  76. }
  77. assert(PyExceptionInstance_Check(value));
  78. if (traceback != NULL && !PyTraceBack_Check(traceback)) {
  79. if (traceback == Py_None) {
  80. Py_DECREF(Py_None);
  81. traceback = NULL;
  82. }
  83. else {
  84. PyErr_SetString(PyExc_TypeError, "traceback must be a Traceback or None");
  85. Py_XDECREF(value);
  86. Py_DECREF(type);
  87. Py_XDECREF(traceback);
  88. return;
  89. }
  90. }
  91. PyObject *old_traceback = ((PyBaseExceptionObject *)value)->traceback;
  92. ((PyBaseExceptionObject *)value)->traceback = traceback;
  93. Py_XDECREF(old_traceback);
  94. _PyErr_SetRaisedException(tstate, value);
  95. Py_DECREF(type);
  96. }
  97. void
  98. PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
  99. {
  100. PyThreadState *tstate = _PyThreadState_GET();
  101. _PyErr_Restore(tstate, type, value, traceback);
  102. }
  103. void
  104. PyErr_SetRaisedException(PyObject *exc)
  105. {
  106. PyThreadState *tstate = _PyThreadState_GET();
  107. _PyErr_SetRaisedException(tstate, exc);
  108. }
  109. _PyErr_StackItem *
  110. _PyErr_GetTopmostException(PyThreadState *tstate)
  111. {
  112. _PyErr_StackItem *exc_info = tstate->exc_info;
  113. assert(exc_info);
  114. while ((exc_info->exc_value == NULL || exc_info->exc_value == Py_None) &&
  115. exc_info->previous_item != NULL)
  116. {
  117. exc_info = exc_info->previous_item;
  118. }
  119. return exc_info;
  120. }
  121. static PyObject *
  122. get_normalization_failure_note(PyThreadState *tstate, PyObject *exception, PyObject *value)
  123. {
  124. PyObject *args = PyObject_Repr(value);
  125. if (args == NULL) {
  126. _PyErr_Clear(tstate);
  127. args = PyUnicode_FromFormat("<unknown>");
  128. }
  129. PyObject *note;
  130. const char *tpname = ((PyTypeObject*)exception)->tp_name;
  131. if (args == NULL) {
  132. _PyErr_Clear(tstate);
  133. note = PyUnicode_FromFormat("Normalization failed: type=%s", tpname);
  134. }
  135. else {
  136. note = PyUnicode_FromFormat("Normalization failed: type=%s args=%S",
  137. tpname, args);
  138. Py_DECREF(args);
  139. }
  140. return note;
  141. }
  142. void
  143. _PyErr_SetObject(PyThreadState *tstate, PyObject *exception, PyObject *value)
  144. {
  145. PyObject *exc_value;
  146. PyObject *tb = NULL;
  147. if (exception != NULL &&
  148. !PyExceptionClass_Check(exception)) {
  149. _PyErr_Format(tstate, PyExc_SystemError,
  150. "_PyErr_SetObject: "
  151. "exception %R is not a BaseException subclass",
  152. exception);
  153. return;
  154. }
  155. /* Normalize the exception */
  156. int is_subclass = 0;
  157. if (value != NULL && PyExceptionInstance_Check(value)) {
  158. is_subclass = PyObject_IsSubclass((PyObject *)Py_TYPE(value), exception);
  159. if (is_subclass < 0) {
  160. return;
  161. }
  162. }
  163. Py_XINCREF(value);
  164. if (!is_subclass) {
  165. /* We must normalize the value right now */
  166. /* Issue #23571: functions must not be called with an
  167. exception set */
  168. _PyErr_Clear(tstate);
  169. PyObject *fixed_value = _PyErr_CreateException(exception, value);
  170. if (fixed_value == NULL) {
  171. PyObject *exc = _PyErr_GetRaisedException(tstate);
  172. assert(PyExceptionInstance_Check(exc));
  173. PyObject *note = get_normalization_failure_note(tstate, exception, value);
  174. Py_XDECREF(value);
  175. if (note != NULL) {
  176. /* ignore errors in _PyException_AddNote - they will be overwritten below */
  177. _PyException_AddNote(exc, note);
  178. Py_DECREF(note);
  179. }
  180. _PyErr_SetRaisedException(tstate, exc);
  181. return;
  182. }
  183. Py_XSETREF(value, fixed_value);
  184. }
  185. exc_value = _PyErr_GetTopmostException(tstate)->exc_value;
  186. if (exc_value != NULL && exc_value != Py_None) {
  187. /* Implicit exception chaining */
  188. Py_INCREF(exc_value);
  189. /* Avoid creating new reference cycles through the
  190. context chain, while taking care not to hang on
  191. pre-existing ones.
  192. This is O(chain length) but context chains are
  193. usually very short. Sensitive readers may try
  194. to inline the call to PyException_GetContext. */
  195. if (exc_value != value) {
  196. PyObject *o = exc_value, *context;
  197. PyObject *slow_o = o; /* Floyd's cycle detection algo */
  198. int slow_update_toggle = 0;
  199. while ((context = PyException_GetContext(o))) {
  200. Py_DECREF(context);
  201. if (context == value) {
  202. PyException_SetContext(o, NULL);
  203. break;
  204. }
  205. o = context;
  206. if (o == slow_o) {
  207. /* pre-existing cycle - all exceptions on the
  208. path were visited and checked. */
  209. break;
  210. }
  211. if (slow_update_toggle) {
  212. slow_o = PyException_GetContext(slow_o);
  213. Py_DECREF(slow_o);
  214. }
  215. slow_update_toggle = !slow_update_toggle;
  216. }
  217. PyException_SetContext(value, exc_value);
  218. }
  219. else {
  220. Py_DECREF(exc_value);
  221. }
  222. }
  223. assert(value != NULL);
  224. if (PyExceptionInstance_Check(value))
  225. tb = PyException_GetTraceback(value);
  226. _PyErr_Restore(tstate, Py_NewRef(Py_TYPE(value)), value, tb);
  227. }
  228. void
  229. PyErr_SetObject(PyObject *exception, PyObject *value)
  230. {
  231. PyThreadState *tstate = _PyThreadState_GET();
  232. _PyErr_SetObject(tstate, exception, value);
  233. }
  234. /* Set a key error with the specified argument, wrapping it in a
  235. * tuple automatically so that tuple keys are not unpacked as the
  236. * exception arguments. */
  237. void
  238. _PyErr_SetKeyError(PyObject *arg)
  239. {
  240. PyThreadState *tstate = _PyThreadState_GET();
  241. PyObject *tup = PyTuple_Pack(1, arg);
  242. if (!tup) {
  243. /* caller will expect error to be set anyway */
  244. return;
  245. }
  246. _PyErr_SetObject(tstate, PyExc_KeyError, tup);
  247. Py_DECREF(tup);
  248. }
  249. void
  250. _PyErr_SetNone(PyThreadState *tstate, PyObject *exception)
  251. {
  252. _PyErr_SetObject(tstate, exception, (PyObject *)NULL);
  253. }
  254. void
  255. PyErr_SetNone(PyObject *exception)
  256. {
  257. PyThreadState *tstate = _PyThreadState_GET();
  258. _PyErr_SetNone(tstate, exception);
  259. }
  260. void
  261. _PyErr_SetString(PyThreadState *tstate, PyObject *exception,
  262. const char *string)
  263. {
  264. PyObject *value = PyUnicode_FromString(string);
  265. if (value != NULL) {
  266. _PyErr_SetObject(tstate, exception, value);
  267. Py_DECREF(value);
  268. }
  269. }
  270. void
  271. PyErr_SetString(PyObject *exception, const char *string)
  272. {
  273. PyThreadState *tstate = _PyThreadState_GET();
  274. _PyErr_SetString(tstate, exception, string);
  275. }
  276. void
  277. _PyErr_SetLocaleString(PyObject *exception, const char *string)
  278. {
  279. PyObject *value = PyUnicode_DecodeLocale(string, "surrogateescape");
  280. if (value != NULL) {
  281. PyErr_SetObject(exception, value);
  282. Py_DECREF(value);
  283. }
  284. }
  285. PyObject* _Py_HOT_FUNCTION
  286. PyErr_Occurred(void)
  287. {
  288. /* The caller must hold the GIL. */
  289. assert(PyGILState_Check());
  290. PyThreadState *tstate = _PyThreadState_GET();
  291. return _PyErr_Occurred(tstate);
  292. }
  293. int
  294. PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
  295. {
  296. if (err == NULL || exc == NULL) {
  297. /* maybe caused by "import exceptions" that failed early on */
  298. return 0;
  299. }
  300. if (PyTuple_Check(exc)) {
  301. Py_ssize_t i, n;
  302. n = PyTuple_Size(exc);
  303. for (i = 0; i < n; i++) {
  304. /* Test recursively */
  305. if (PyErr_GivenExceptionMatches(
  306. err, PyTuple_GET_ITEM(exc, i)))
  307. {
  308. return 1;
  309. }
  310. }
  311. return 0;
  312. }
  313. /* err might be an instance, so check its class. */
  314. if (PyExceptionInstance_Check(err))
  315. err = PyExceptionInstance_Class(err);
  316. if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
  317. return PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc);
  318. }
  319. return err == exc;
  320. }
  321. int
  322. _PyErr_ExceptionMatches(PyThreadState *tstate, PyObject *exc)
  323. {
  324. return PyErr_GivenExceptionMatches(_PyErr_Occurred(tstate), exc);
  325. }
  326. int
  327. PyErr_ExceptionMatches(PyObject *exc)
  328. {
  329. PyThreadState *tstate = _PyThreadState_GET();
  330. return _PyErr_ExceptionMatches(tstate, exc);
  331. }
  332. #ifndef Py_NORMALIZE_RECURSION_LIMIT
  333. #define Py_NORMALIZE_RECURSION_LIMIT 32
  334. #endif
  335. /* Used in many places to normalize a raised exception, including in
  336. eval_code2(), do_raise(), and PyErr_Print()
  337. XXX: should PyErr_NormalizeException() also call
  338. PyException_SetTraceback() with the resulting value and tb?
  339. */
  340. void
  341. _PyErr_NormalizeException(PyThreadState *tstate, PyObject **exc,
  342. PyObject **val, PyObject **tb)
  343. {
  344. int recursion_depth = 0;
  345. tstate->recursion_headroom++;
  346. PyObject *type, *value, *initial_tb;
  347. restart:
  348. type = *exc;
  349. if (type == NULL) {
  350. /* There was no exception, so nothing to do. */
  351. tstate->recursion_headroom--;
  352. return;
  353. }
  354. value = *val;
  355. /* If PyErr_SetNone() was used, the value will have been actually
  356. set to NULL.
  357. */
  358. if (!value) {
  359. value = Py_NewRef(Py_None);
  360. }
  361. /* Normalize the exception so that if the type is a class, the
  362. value will be an instance.
  363. */
  364. if (PyExceptionClass_Check(type)) {
  365. PyObject *inclass = NULL;
  366. int is_subclass = 0;
  367. if (PyExceptionInstance_Check(value)) {
  368. inclass = PyExceptionInstance_Class(value);
  369. is_subclass = PyObject_IsSubclass(inclass, type);
  370. if (is_subclass < 0) {
  371. goto error;
  372. }
  373. }
  374. /* If the value was not an instance, or is not an instance
  375. whose class is (or is derived from) type, then use the
  376. value as an argument to instantiation of the type
  377. class.
  378. */
  379. if (!is_subclass) {
  380. PyObject *fixed_value = _PyErr_CreateException(type, value);
  381. if (fixed_value == NULL) {
  382. goto error;
  383. }
  384. Py_SETREF(value, fixed_value);
  385. }
  386. /* If the class of the instance doesn't exactly match the
  387. class of the type, believe the instance.
  388. */
  389. else if (inclass != type) {
  390. Py_SETREF(type, Py_NewRef(inclass));
  391. }
  392. }
  393. *exc = type;
  394. *val = value;
  395. tstate->recursion_headroom--;
  396. return;
  397. error:
  398. Py_DECREF(type);
  399. Py_DECREF(value);
  400. recursion_depth++;
  401. if (recursion_depth == Py_NORMALIZE_RECURSION_LIMIT) {
  402. _PyErr_SetString(tstate, PyExc_RecursionError,
  403. "maximum recursion depth exceeded "
  404. "while normalizing an exception");
  405. }
  406. /* If the new exception doesn't set a traceback and the old
  407. exception had a traceback, use the old traceback for the
  408. new exception. It's better than nothing.
  409. */
  410. initial_tb = *tb;
  411. _PyErr_Fetch(tstate, exc, val, tb);
  412. assert(*exc != NULL);
  413. if (initial_tb != NULL) {
  414. if (*tb == NULL)
  415. *tb = initial_tb;
  416. else
  417. Py_DECREF(initial_tb);
  418. }
  419. /* Abort when Py_NORMALIZE_RECURSION_LIMIT has been exceeded, and the
  420. corresponding RecursionError could not be normalized, and the
  421. MemoryError raised when normalize this RecursionError could not be
  422. normalized. */
  423. if (recursion_depth >= Py_NORMALIZE_RECURSION_LIMIT + 2) {
  424. if (PyErr_GivenExceptionMatches(*exc, PyExc_MemoryError)) {
  425. Py_FatalError("Cannot recover from MemoryErrors "
  426. "while normalizing exceptions.");
  427. }
  428. else {
  429. Py_FatalError("Cannot recover from the recursive normalization "
  430. "of an exception.");
  431. }
  432. }
  433. goto restart;
  434. }
  435. void
  436. PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
  437. {
  438. PyThreadState *tstate = _PyThreadState_GET();
  439. _PyErr_NormalizeException(tstate, exc, val, tb);
  440. }
  441. PyObject *
  442. _PyErr_GetRaisedException(PyThreadState *tstate) {
  443. PyObject *exc = tstate->current_exception;
  444. tstate->current_exception = NULL;
  445. return exc;
  446. }
  447. PyObject *
  448. PyErr_GetRaisedException(void)
  449. {
  450. PyThreadState *tstate = _PyThreadState_GET();
  451. return _PyErr_GetRaisedException(tstate);
  452. }
  453. void
  454. _PyErr_Fetch(PyThreadState *tstate, PyObject **p_type, PyObject **p_value,
  455. PyObject **p_traceback)
  456. {
  457. PyObject *exc = _PyErr_GetRaisedException(tstate);
  458. *p_value = exc;
  459. if (exc == NULL) {
  460. *p_type = NULL;
  461. *p_traceback = NULL;
  462. }
  463. else {
  464. *p_type = Py_NewRef(Py_TYPE(exc));
  465. *p_traceback = Py_XNewRef(((PyBaseExceptionObject *)exc)->traceback);
  466. }
  467. }
  468. void
  469. PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
  470. {
  471. PyThreadState *tstate = _PyThreadState_GET();
  472. _PyErr_Fetch(tstate, p_type, p_value, p_traceback);
  473. }
  474. void
  475. _PyErr_Clear(PyThreadState *tstate)
  476. {
  477. _PyErr_Restore(tstate, NULL, NULL, NULL);
  478. }
  479. void
  480. PyErr_Clear(void)
  481. {
  482. PyThreadState *tstate = _PyThreadState_GET();
  483. _PyErr_Clear(tstate);
  484. }
  485. static PyObject*
  486. get_exc_type(PyObject *exc_value) /* returns a borrowed ref */
  487. {
  488. if (exc_value == NULL || exc_value == Py_None) {
  489. return Py_None;
  490. }
  491. else {
  492. assert(PyExceptionInstance_Check(exc_value));
  493. PyObject *type = PyExceptionInstance_Class(exc_value);
  494. assert(type != NULL);
  495. return type;
  496. }
  497. }
  498. static PyObject*
  499. get_exc_traceback(PyObject *exc_value) /* returns a borrowed ref */
  500. {
  501. if (exc_value == NULL || exc_value == Py_None) {
  502. return Py_None;
  503. }
  504. else {
  505. assert(PyExceptionInstance_Check(exc_value));
  506. PyObject *tb = PyException_GetTraceback(exc_value);
  507. Py_XDECREF(tb);
  508. return tb ? tb : Py_None;
  509. }
  510. }
  511. void
  512. _PyErr_GetExcInfo(PyThreadState *tstate,
  513. PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
  514. {
  515. _PyErr_StackItem *exc_info = _PyErr_GetTopmostException(tstate);
  516. *p_type = Py_XNewRef(get_exc_type(exc_info->exc_value));
  517. *p_value = Py_XNewRef(exc_info->exc_value);
  518. *p_traceback = Py_XNewRef(get_exc_traceback(exc_info->exc_value));
  519. }
  520. PyObject*
  521. _PyErr_GetHandledException(PyThreadState *tstate)
  522. {
  523. _PyErr_StackItem *exc_info = _PyErr_GetTopmostException(tstate);
  524. PyObject *exc = exc_info->exc_value;
  525. if (exc == NULL || exc == Py_None) {
  526. return NULL;
  527. }
  528. return Py_NewRef(exc);
  529. }
  530. PyObject*
  531. PyErr_GetHandledException(void)
  532. {
  533. PyThreadState *tstate = _PyThreadState_GET();
  534. return _PyErr_GetHandledException(tstate);
  535. }
  536. void
  537. _PyErr_SetHandledException(PyThreadState *tstate, PyObject *exc)
  538. {
  539. Py_XSETREF(tstate->exc_info->exc_value, Py_XNewRef(exc));
  540. }
  541. void
  542. PyErr_SetHandledException(PyObject *exc)
  543. {
  544. PyThreadState *tstate = _PyThreadState_GET();
  545. _PyErr_SetHandledException(tstate, exc);
  546. }
  547. void
  548. PyErr_GetExcInfo(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
  549. {
  550. PyThreadState *tstate = _PyThreadState_GET();
  551. _PyErr_GetExcInfo(tstate, p_type, p_value, p_traceback);
  552. }
  553. void
  554. PyErr_SetExcInfo(PyObject *type, PyObject *value, PyObject *traceback)
  555. {
  556. PyErr_SetHandledException(value);
  557. Py_XDECREF(value);
  558. /* These args are no longer used, but we still need to steal a ref */
  559. Py_XDECREF(type);
  560. Py_XDECREF(traceback);
  561. }
  562. PyObject*
  563. _PyErr_StackItemToExcInfoTuple(_PyErr_StackItem *err_info)
  564. {
  565. PyObject *exc_value = err_info->exc_value;
  566. assert(exc_value == NULL ||
  567. exc_value == Py_None ||
  568. PyExceptionInstance_Check(exc_value));
  569. PyObject *exc_type = get_exc_type(exc_value);
  570. PyObject *exc_traceback = get_exc_traceback(exc_value);
  571. return Py_BuildValue(
  572. "(OOO)",
  573. exc_type ? exc_type : Py_None,
  574. exc_value ? exc_value : Py_None,
  575. exc_traceback ? exc_traceback : Py_None);
  576. }
  577. /* Like PyErr_Restore(), but if an exception is already set,
  578. set the context associated with it.
  579. The caller is responsible for ensuring that this call won't create
  580. any cycles in the exception context chain. */
  581. void
  582. _PyErr_ChainExceptions(PyObject *typ, PyObject *val, PyObject *tb)
  583. {
  584. if (typ == NULL)
  585. return;
  586. PyThreadState *tstate = _PyThreadState_GET();
  587. if (!PyExceptionClass_Check(typ)) {
  588. _PyErr_Format(tstate, PyExc_SystemError,
  589. "_PyErr_ChainExceptions: "
  590. "exception %R is not a BaseException subclass",
  591. typ);
  592. return;
  593. }
  594. if (_PyErr_Occurred(tstate)) {
  595. _PyErr_NormalizeException(tstate, &typ, &val, &tb);
  596. if (tb != NULL) {
  597. PyException_SetTraceback(val, tb);
  598. Py_DECREF(tb);
  599. }
  600. Py_DECREF(typ);
  601. PyObject *exc2 = _PyErr_GetRaisedException(tstate);
  602. PyException_SetContext(exc2, val);
  603. _PyErr_SetRaisedException(tstate, exc2);
  604. }
  605. else {
  606. _PyErr_Restore(tstate, typ, val, tb);
  607. }
  608. }
  609. /* Like PyErr_SetRaisedException(), but if an exception is already set,
  610. set the context associated with it.
  611. The caller is responsible for ensuring that this call won't create
  612. any cycles in the exception context chain. */
  613. void
  614. _PyErr_ChainExceptions1(PyObject *exc)
  615. {
  616. if (exc == NULL) {
  617. return;
  618. }
  619. PyThreadState *tstate = _PyThreadState_GET();
  620. if (_PyErr_Occurred(tstate)) {
  621. PyObject *exc2 = _PyErr_GetRaisedException(tstate);
  622. PyException_SetContext(exc2, exc);
  623. _PyErr_SetRaisedException(tstate, exc2);
  624. }
  625. else {
  626. _PyErr_SetRaisedException(tstate, exc);
  627. }
  628. }
  629. /* Set the currently set exception's context to the given exception.
  630. If the provided exc_info is NULL, then the current Python thread state's
  631. exc_info will be used for the context instead.
  632. This function can only be called when _PyErr_Occurred() is true.
  633. Also, this function won't create any cycles in the exception context
  634. chain to the extent that _PyErr_SetObject ensures this. */
  635. void
  636. _PyErr_ChainStackItem(_PyErr_StackItem *exc_info)
  637. {
  638. PyThreadState *tstate = _PyThreadState_GET();
  639. assert(_PyErr_Occurred(tstate));
  640. int exc_info_given;
  641. if (exc_info == NULL) {
  642. exc_info_given = 0;
  643. exc_info = tstate->exc_info;
  644. } else {
  645. exc_info_given = 1;
  646. }
  647. if (exc_info->exc_value == NULL || exc_info->exc_value == Py_None) {
  648. return;
  649. }
  650. _PyErr_StackItem *saved_exc_info;
  651. if (exc_info_given) {
  652. /* Temporarily set the thread state's exc_info since this is what
  653. _PyErr_SetObject uses for implicit exception chaining. */
  654. saved_exc_info = tstate->exc_info;
  655. tstate->exc_info = exc_info;
  656. }
  657. PyObject *typ, *val, *tb;
  658. _PyErr_Fetch(tstate, &typ, &val, &tb);
  659. /* _PyErr_SetObject sets the context from PyThreadState. */
  660. _PyErr_SetObject(tstate, typ, val);
  661. Py_DECREF(typ); // since _PyErr_Occurred was true
  662. Py_XDECREF(val);
  663. Py_XDECREF(tb);
  664. if (exc_info_given) {
  665. tstate->exc_info = saved_exc_info;
  666. }
  667. }
  668. static PyObject *
  669. _PyErr_FormatVFromCause(PyThreadState *tstate, PyObject *exception,
  670. const char *format, va_list vargs)
  671. {
  672. assert(_PyErr_Occurred(tstate));
  673. PyObject *exc = _PyErr_GetRaisedException(tstate);
  674. assert(!_PyErr_Occurred(tstate));
  675. _PyErr_FormatV(tstate, exception, format, vargs);
  676. PyObject *exc2 = _PyErr_GetRaisedException(tstate);
  677. PyException_SetCause(exc2, Py_NewRef(exc));
  678. PyException_SetContext(exc2, Py_NewRef(exc));
  679. Py_DECREF(exc);
  680. _PyErr_SetRaisedException(tstate, exc2);
  681. return NULL;
  682. }
  683. PyObject *
  684. _PyErr_FormatFromCauseTstate(PyThreadState *tstate, PyObject *exception,
  685. const char *format, ...)
  686. {
  687. va_list vargs;
  688. va_start(vargs, format);
  689. _PyErr_FormatVFromCause(tstate, exception, format, vargs);
  690. va_end(vargs);
  691. return NULL;
  692. }
  693. PyObject *
  694. _PyErr_FormatFromCause(PyObject *exception, const char *format, ...)
  695. {
  696. PyThreadState *tstate = _PyThreadState_GET();
  697. va_list vargs;
  698. va_start(vargs, format);
  699. _PyErr_FormatVFromCause(tstate, exception, format, vargs);
  700. va_end(vargs);
  701. return NULL;
  702. }
  703. /* Convenience functions to set a type error exception and return 0 */
  704. int
  705. PyErr_BadArgument(void)
  706. {
  707. PyThreadState *tstate = _PyThreadState_GET();
  708. _PyErr_SetString(tstate, PyExc_TypeError,
  709. "bad argument type for built-in operation");
  710. return 0;
  711. }
  712. PyObject *
  713. PyErr_NoMemory(void)
  714. {
  715. PyThreadState *tstate = _PyThreadState_GET();
  716. return _PyErr_NoMemory(tstate);
  717. }
  718. PyObject *
  719. PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
  720. {
  721. return PyErr_SetFromErrnoWithFilenameObjects(exc, filenameObject, NULL);
  722. }
  723. PyObject *
  724. PyErr_SetFromErrnoWithFilenameObjects(PyObject *exc, PyObject *filenameObject, PyObject *filenameObject2)
  725. {
  726. PyThreadState *tstate = _PyThreadState_GET();
  727. PyObject *message;
  728. PyObject *v, *args;
  729. int i = errno;
  730. #ifdef MS_WINDOWS
  731. WCHAR *s_buf = NULL;
  732. #endif /* Unix/Windows */
  733. #ifdef EINTR
  734. if (i == EINTR && PyErr_CheckSignals())
  735. return NULL;
  736. #endif
  737. #ifndef MS_WINDOWS
  738. if (i != 0) {
  739. const char *s = strerror(i);
  740. message = PyUnicode_DecodeLocale(s, "surrogateescape");
  741. }
  742. else {
  743. /* Sometimes errno didn't get set */
  744. message = PyUnicode_FromString("Error");
  745. }
  746. #else
  747. if (i == 0)
  748. message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */
  749. else
  750. {
  751. /* Note that the Win32 errors do not lineup with the
  752. errno error. So if the error is in the MSVC error
  753. table, we use it, otherwise we assume it really _is_
  754. a Win32 error code
  755. */
  756. if (i > 0 && i < _sys_nerr) {
  757. message = PyUnicode_FromString(_sys_errlist[i]);
  758. }
  759. else {
  760. int len = FormatMessageW(
  761. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  762. FORMAT_MESSAGE_FROM_SYSTEM |
  763. FORMAT_MESSAGE_IGNORE_INSERTS,
  764. NULL, /* no message source */
  765. i,
  766. MAKELANGID(LANG_NEUTRAL,
  767. SUBLANG_DEFAULT),
  768. /* Default language */
  769. (LPWSTR) &s_buf,
  770. 0, /* size not used */
  771. NULL); /* no args */
  772. if (len==0) {
  773. /* Only ever seen this in out-of-mem
  774. situations */
  775. s_buf = NULL;
  776. message = PyUnicode_FromFormat("Windows Error 0x%x", i);
  777. } else {
  778. /* remove trailing cr/lf and dots */
  779. while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
  780. s_buf[--len] = L'\0';
  781. message = PyUnicode_FromWideChar(s_buf, len);
  782. }
  783. }
  784. }
  785. #endif /* Unix/Windows */
  786. if (message == NULL)
  787. {
  788. #ifdef MS_WINDOWS
  789. LocalFree(s_buf);
  790. #endif
  791. return NULL;
  792. }
  793. if (filenameObject != NULL) {
  794. if (filenameObject2 != NULL)
  795. args = Py_BuildValue("(iOOiO)", i, message, filenameObject, 0, filenameObject2);
  796. else
  797. args = Py_BuildValue("(iOO)", i, message, filenameObject);
  798. } else {
  799. assert(filenameObject2 == NULL);
  800. args = Py_BuildValue("(iO)", i, message);
  801. }
  802. Py_DECREF(message);
  803. if (args != NULL) {
  804. v = PyObject_Call(exc, args, NULL);
  805. Py_DECREF(args);
  806. if (v != NULL) {
  807. _PyErr_SetObject(tstate, (PyObject *) Py_TYPE(v), v);
  808. Py_DECREF(v);
  809. }
  810. }
  811. #ifdef MS_WINDOWS
  812. LocalFree(s_buf);
  813. #endif
  814. return NULL;
  815. }
  816. PyObject *
  817. PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
  818. {
  819. PyObject *name = NULL;
  820. if (filename) {
  821. int i = errno;
  822. name = PyUnicode_DecodeFSDefault(filename);
  823. if (name == NULL) {
  824. return NULL;
  825. }
  826. errno = i;
  827. }
  828. PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
  829. Py_XDECREF(name);
  830. return result;
  831. }
  832. PyObject *
  833. PyErr_SetFromErrno(PyObject *exc)
  834. {
  835. return PyErr_SetFromErrnoWithFilenameObjects(exc, NULL, NULL);
  836. }
  837. #ifdef MS_WINDOWS
  838. /* Windows specific error code handling */
  839. PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
  840. PyObject *exc,
  841. int ierr,
  842. PyObject *filenameObject)
  843. {
  844. return PyErr_SetExcFromWindowsErrWithFilenameObjects(exc, ierr,
  845. filenameObject, NULL);
  846. }
  847. PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(
  848. PyObject *exc,
  849. int ierr,
  850. PyObject *filenameObject,
  851. PyObject *filenameObject2)
  852. {
  853. PyThreadState *tstate = _PyThreadState_GET();
  854. int len;
  855. WCHAR *s_buf = NULL; /* Free via LocalFree */
  856. PyObject *message;
  857. PyObject *args, *v;
  858. DWORD err = (DWORD)ierr;
  859. if (err==0) {
  860. err = GetLastError();
  861. }
  862. len = FormatMessageW(
  863. /* Error API error */
  864. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  865. FORMAT_MESSAGE_FROM_SYSTEM |
  866. FORMAT_MESSAGE_IGNORE_INSERTS,
  867. NULL, /* no message source */
  868. err,
  869. MAKELANGID(LANG_NEUTRAL,
  870. SUBLANG_DEFAULT), /* Default language */
  871. (LPWSTR) &s_buf,
  872. 0, /* size not used */
  873. NULL); /* no args */
  874. if (len==0) {
  875. /* Only seen this in out of mem situations */
  876. message = PyUnicode_FromFormat("Windows Error 0x%x", err);
  877. s_buf = NULL;
  878. } else {
  879. /* remove trailing cr/lf and dots */
  880. while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
  881. s_buf[--len] = L'\0';
  882. message = PyUnicode_FromWideChar(s_buf, len);
  883. }
  884. if (message == NULL)
  885. {
  886. LocalFree(s_buf);
  887. return NULL;
  888. }
  889. if (filenameObject == NULL) {
  890. assert(filenameObject2 == NULL);
  891. filenameObject = filenameObject2 = Py_None;
  892. }
  893. else if (filenameObject2 == NULL)
  894. filenameObject2 = Py_None;
  895. /* This is the constructor signature for OSError.
  896. The POSIX translation will be figured out by the constructor. */
  897. args = Py_BuildValue("(iOOiO)", 0, message, filenameObject, err, filenameObject2);
  898. Py_DECREF(message);
  899. if (args != NULL) {
  900. v = PyObject_Call(exc, args, NULL);
  901. Py_DECREF(args);
  902. if (v != NULL) {
  903. _PyErr_SetObject(tstate, (PyObject *) Py_TYPE(v), v);
  904. Py_DECREF(v);
  905. }
  906. }
  907. LocalFree(s_buf);
  908. return NULL;
  909. }
  910. PyObject *PyErr_SetExcFromWindowsErrWithFilename(
  911. PyObject *exc,
  912. int ierr,
  913. const char *filename)
  914. {
  915. PyObject *name = NULL;
  916. if (filename) {
  917. if ((DWORD)ierr == 0) {
  918. ierr = (int)GetLastError();
  919. }
  920. name = PyUnicode_DecodeFSDefault(filename);
  921. if (name == NULL) {
  922. return NULL;
  923. }
  924. }
  925. PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
  926. ierr,
  927. name,
  928. NULL);
  929. Py_XDECREF(name);
  930. return ret;
  931. }
  932. PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
  933. {
  934. return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
  935. }
  936. PyObject *PyErr_SetFromWindowsErr(int ierr)
  937. {
  938. return PyErr_SetExcFromWindowsErrWithFilename(PyExc_OSError,
  939. ierr, NULL);
  940. }
  941. PyObject *PyErr_SetFromWindowsErrWithFilename(
  942. int ierr,
  943. const char *filename)
  944. {
  945. PyObject *name = NULL;
  946. if (filename) {
  947. if ((DWORD)ierr == 0) {
  948. ierr = (int)GetLastError();
  949. }
  950. name = PyUnicode_DecodeFSDefault(filename);
  951. if (name == NULL) {
  952. return NULL;
  953. }
  954. }
  955. PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
  956. PyExc_OSError,
  957. ierr, name, NULL);
  958. Py_XDECREF(name);
  959. return result;
  960. }
  961. #endif /* MS_WINDOWS */
  962. static PyObject *
  963. _PyErr_SetImportErrorSubclassWithNameFrom(
  964. PyObject *exception, PyObject *msg,
  965. PyObject *name, PyObject *path, PyObject* from_name)
  966. {
  967. PyThreadState *tstate = _PyThreadState_GET();
  968. int issubclass;
  969. PyObject *kwargs, *error;
  970. issubclass = PyObject_IsSubclass(exception, PyExc_ImportError);
  971. if (issubclass < 0) {
  972. return NULL;
  973. }
  974. else if (!issubclass) {
  975. _PyErr_SetString(tstate, PyExc_TypeError,
  976. "expected a subclass of ImportError");
  977. return NULL;
  978. }
  979. if (msg == NULL) {
  980. _PyErr_SetString(tstate, PyExc_TypeError,
  981. "expected a message argument");
  982. return NULL;
  983. }
  984. if (name == NULL) {
  985. name = Py_None;
  986. }
  987. if (path == NULL) {
  988. path = Py_None;
  989. }
  990. if (from_name == NULL) {
  991. from_name = Py_None;
  992. }
  993. kwargs = PyDict_New();
  994. if (kwargs == NULL) {
  995. return NULL;
  996. }
  997. if (PyDict_SetItemString(kwargs, "name", name) < 0) {
  998. goto done;
  999. }
  1000. if (PyDict_SetItemString(kwargs, "path", path) < 0) {
  1001. goto done;
  1002. }
  1003. if (PyDict_SetItemString(kwargs, "name_from", from_name) < 0) {
  1004. goto done;
  1005. }
  1006. error = PyObject_VectorcallDict(exception, &msg, 1, kwargs);
  1007. if (error != NULL) {
  1008. _PyErr_SetObject(tstate, (PyObject *)Py_TYPE(error), error);
  1009. Py_DECREF(error);
  1010. }
  1011. done:
  1012. Py_DECREF(kwargs);
  1013. return NULL;
  1014. }
  1015. PyObject *
  1016. PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg,
  1017. PyObject *name, PyObject *path)
  1018. {
  1019. return _PyErr_SetImportErrorSubclassWithNameFrom(exception, msg, name, path, NULL);
  1020. }
  1021. PyObject *
  1022. _PyErr_SetImportErrorWithNameFrom(PyObject *msg, PyObject *name, PyObject *path, PyObject* from_name)
  1023. {
  1024. return _PyErr_SetImportErrorSubclassWithNameFrom(PyExc_ImportError, msg, name, path, from_name);
  1025. }
  1026. PyObject *
  1027. PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
  1028. {
  1029. return PyErr_SetImportErrorSubclass(PyExc_ImportError, msg, name, path);
  1030. }
  1031. void
  1032. _PyErr_BadInternalCall(const char *filename, int lineno)
  1033. {
  1034. PyThreadState *tstate = _PyThreadState_GET();
  1035. _PyErr_Format(tstate, PyExc_SystemError,
  1036. "%s:%d: bad argument to internal function",
  1037. filename, lineno);
  1038. }
  1039. /* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
  1040. export the entry point for existing object code: */
  1041. #undef PyErr_BadInternalCall
  1042. void
  1043. PyErr_BadInternalCall(void)
  1044. {
  1045. assert(0 && "bad argument to internal function");
  1046. PyThreadState *tstate = _PyThreadState_GET();
  1047. _PyErr_SetString(tstate, PyExc_SystemError,
  1048. "bad argument to internal function");
  1049. }
  1050. #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
  1051. static PyObject *
  1052. _PyErr_FormatV(PyThreadState *tstate, PyObject *exception,
  1053. const char *format, va_list vargs)
  1054. {
  1055. PyObject* string;
  1056. /* Issue #23571: PyUnicode_FromFormatV() must not be called with an
  1057. exception set, it calls arbitrary Python code like PyObject_Repr() */
  1058. _PyErr_Clear(tstate);
  1059. string = PyUnicode_FromFormatV(format, vargs);
  1060. if (string != NULL) {
  1061. _PyErr_SetObject(tstate, exception, string);
  1062. Py_DECREF(string);
  1063. }
  1064. return NULL;
  1065. }
  1066. PyObject *
  1067. PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
  1068. {
  1069. PyThreadState *tstate = _PyThreadState_GET();
  1070. return _PyErr_FormatV(tstate, exception, format, vargs);
  1071. }
  1072. PyObject *
  1073. _PyErr_Format(PyThreadState *tstate, PyObject *exception,
  1074. const char *format, ...)
  1075. {
  1076. va_list vargs;
  1077. va_start(vargs, format);
  1078. _PyErr_FormatV(tstate, exception, format, vargs);
  1079. va_end(vargs);
  1080. return NULL;
  1081. }
  1082. PyObject *
  1083. PyErr_Format(PyObject *exception, const char *format, ...)
  1084. {
  1085. PyThreadState *tstate = _PyThreadState_GET();
  1086. va_list vargs;
  1087. va_start(vargs, format);
  1088. _PyErr_FormatV(tstate, exception, format, vargs);
  1089. va_end(vargs);
  1090. return NULL;
  1091. }
  1092. /* Adds a note to the current exception (if any) */
  1093. void
  1094. _PyErr_FormatNote(const char *format, ...)
  1095. {
  1096. PyObject *exc = PyErr_GetRaisedException();
  1097. if (exc == NULL) {
  1098. return;
  1099. }
  1100. va_list vargs;
  1101. va_start(vargs, format);
  1102. PyObject *note = PyUnicode_FromFormatV(format, vargs);
  1103. va_end(vargs);
  1104. if (note == NULL) {
  1105. goto error;
  1106. }
  1107. int res = _PyException_AddNote(exc, note);
  1108. Py_DECREF(note);
  1109. if (res < 0) {
  1110. goto error;
  1111. }
  1112. PyErr_SetRaisedException(exc);
  1113. return;
  1114. error:
  1115. _PyErr_ChainExceptions1(exc);
  1116. }
  1117. PyObject *
  1118. PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
  1119. {
  1120. PyThreadState *tstate = _PyThreadState_GET();
  1121. PyObject *modulename = NULL;
  1122. PyObject *mydict = NULL;
  1123. PyObject *bases = NULL;
  1124. PyObject *result = NULL;
  1125. #if defined(__has_feature)
  1126. # if __has_feature(memory_sanitizer)
  1127. __msan_unpoison_string(name);
  1128. # endif
  1129. #endif
  1130. const char *dot = strrchr(name, '.');
  1131. if (dot == NULL) {
  1132. _PyErr_SetString(tstate, PyExc_SystemError,
  1133. "PyErr_NewException: name must be module.class");
  1134. return NULL;
  1135. }
  1136. if (base == NULL) {
  1137. base = PyExc_Exception;
  1138. }
  1139. if (dict == NULL) {
  1140. dict = mydict = PyDict_New();
  1141. if (dict == NULL)
  1142. goto failure;
  1143. }
  1144. int r = PyDict_Contains(dict, &_Py_ID(__module__));
  1145. if (r < 0) {
  1146. goto failure;
  1147. }
  1148. if (r == 0) {
  1149. modulename = PyUnicode_FromStringAndSize(name,
  1150. (Py_ssize_t)(dot-name));
  1151. if (modulename == NULL)
  1152. goto failure;
  1153. if (PyDict_SetItem(dict, &_Py_ID(__module__), modulename) != 0)
  1154. goto failure;
  1155. }
  1156. if (PyTuple_Check(base)) {
  1157. bases = Py_NewRef(base);
  1158. } else {
  1159. bases = PyTuple_Pack(1, base);
  1160. if (bases == NULL)
  1161. goto failure;
  1162. }
  1163. /* Create a real class. */
  1164. result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
  1165. dot+1, bases, dict);
  1166. failure:
  1167. Py_XDECREF(bases);
  1168. Py_XDECREF(mydict);
  1169. Py_XDECREF(modulename);
  1170. return result;
  1171. }
  1172. /* Create an exception with docstring */
  1173. PyObject *
  1174. PyErr_NewExceptionWithDoc(const char *name, const char *doc,
  1175. PyObject *base, PyObject *dict)
  1176. {
  1177. int result;
  1178. PyObject *ret = NULL;
  1179. PyObject *mydict = NULL; /* points to the dict only if we create it */
  1180. PyObject *docobj;
  1181. if (dict == NULL) {
  1182. dict = mydict = PyDict_New();
  1183. if (dict == NULL) {
  1184. return NULL;
  1185. }
  1186. }
  1187. if (doc != NULL) {
  1188. docobj = PyUnicode_FromString(doc);
  1189. if (docobj == NULL)
  1190. goto failure;
  1191. result = PyDict_SetItemString(dict, "__doc__", docobj);
  1192. Py_DECREF(docobj);
  1193. if (result < 0)
  1194. goto failure;
  1195. }
  1196. ret = PyErr_NewException(name, base, dict);
  1197. failure:
  1198. Py_XDECREF(mydict);
  1199. return ret;
  1200. }
  1201. PyDoc_STRVAR(UnraisableHookArgs__doc__,
  1202. "UnraisableHookArgs\n\
  1203. \n\
  1204. Type used to pass arguments to sys.unraisablehook.");
  1205. static PyTypeObject UnraisableHookArgsType;
  1206. static PyStructSequence_Field UnraisableHookArgs_fields[] = {
  1207. {"exc_type", "Exception type"},
  1208. {"exc_value", "Exception value"},
  1209. {"exc_traceback", "Exception traceback"},
  1210. {"err_msg", "Error message"},
  1211. {"object", "Object causing the exception"},
  1212. {0}
  1213. };
  1214. static PyStructSequence_Desc UnraisableHookArgs_desc = {
  1215. .name = "UnraisableHookArgs",
  1216. .doc = UnraisableHookArgs__doc__,
  1217. .fields = UnraisableHookArgs_fields,
  1218. .n_in_sequence = 5
  1219. };
  1220. PyStatus
  1221. _PyErr_InitTypes(PyInterpreterState *interp)
  1222. {
  1223. if (_PyStructSequence_InitBuiltin(interp, &UnraisableHookArgsType,
  1224. &UnraisableHookArgs_desc) < 0)
  1225. {
  1226. return _PyStatus_ERR("failed to initialize UnraisableHookArgs type");
  1227. }
  1228. return _PyStatus_OK();
  1229. }
  1230. void
  1231. _PyErr_FiniTypes(PyInterpreterState *interp)
  1232. {
  1233. _PyStructSequence_FiniBuiltin(interp, &UnraisableHookArgsType);
  1234. }
  1235. static PyObject *
  1236. make_unraisable_hook_args(PyThreadState *tstate, PyObject *exc_type,
  1237. PyObject *exc_value, PyObject *exc_tb,
  1238. PyObject *err_msg, PyObject *obj)
  1239. {
  1240. PyObject *args = PyStructSequence_New(&UnraisableHookArgsType);
  1241. if (args == NULL) {
  1242. return NULL;
  1243. }
  1244. Py_ssize_t pos = 0;
  1245. #define ADD_ITEM(exc_type) \
  1246. do { \
  1247. if (exc_type == NULL) { \
  1248. exc_type = Py_None; \
  1249. } \
  1250. PyStructSequence_SET_ITEM(args, pos++, Py_NewRef(exc_type)); \
  1251. } while (0)
  1252. ADD_ITEM(exc_type);
  1253. ADD_ITEM(exc_value);
  1254. ADD_ITEM(exc_tb);
  1255. ADD_ITEM(err_msg);
  1256. ADD_ITEM(obj);
  1257. #undef ADD_ITEM
  1258. if (_PyErr_Occurred(tstate)) {
  1259. Py_DECREF(args);
  1260. return NULL;
  1261. }
  1262. return args;
  1263. }
  1264. /* Default implementation of sys.unraisablehook.
  1265. It can be called to log the exception of a custom sys.unraisablehook.
  1266. Do nothing if sys.stderr attribute doesn't exist or is set to None. */
  1267. static int
  1268. write_unraisable_exc_file(PyThreadState *tstate, PyObject *exc_type,
  1269. PyObject *exc_value, PyObject *exc_tb,
  1270. PyObject *err_msg, PyObject *obj, PyObject *file)
  1271. {
  1272. if (obj != NULL && obj != Py_None) {
  1273. if (err_msg != NULL && err_msg != Py_None) {
  1274. if (PyFile_WriteObject(err_msg, file, Py_PRINT_RAW) < 0) {
  1275. return -1;
  1276. }
  1277. if (PyFile_WriteString(": ", file) < 0) {
  1278. return -1;
  1279. }
  1280. }
  1281. else {
  1282. if (PyFile_WriteString("Exception ignored in: ", file) < 0) {
  1283. return -1;
  1284. }
  1285. }
  1286. if (PyFile_WriteObject(obj, file, 0) < 0) {
  1287. _PyErr_Clear(tstate);
  1288. if (PyFile_WriteString("<object repr() failed>", file) < 0) {
  1289. return -1;
  1290. }
  1291. }
  1292. if (PyFile_WriteString("\n", file) < 0) {
  1293. return -1;
  1294. }
  1295. }
  1296. else if (err_msg != NULL && err_msg != Py_None) {
  1297. if (PyFile_WriteObject(err_msg, file, Py_PRINT_RAW) < 0) {
  1298. return -1;
  1299. }
  1300. if (PyFile_WriteString(":\n", file) < 0) {
  1301. return -1;
  1302. }
  1303. }
  1304. if (exc_tb != NULL && exc_tb != Py_None) {
  1305. if (PyTraceBack_Print(exc_tb, file) < 0) {
  1306. /* continue even if writing the traceback failed */
  1307. _PyErr_Clear(tstate);
  1308. }
  1309. }
  1310. if (exc_type == NULL || exc_type == Py_None) {
  1311. return -1;
  1312. }
  1313. assert(PyExceptionClass_Check(exc_type));
  1314. PyObject *modulename = PyObject_GetAttr(exc_type, &_Py_ID(__module__));
  1315. if (modulename == NULL || !PyUnicode_Check(modulename)) {
  1316. Py_XDECREF(modulename);
  1317. _PyErr_Clear(tstate);
  1318. if (PyFile_WriteString("<unknown>", file) < 0) {
  1319. return -1;
  1320. }
  1321. }
  1322. else {
  1323. if (!_PyUnicode_Equal(modulename, &_Py_ID(builtins)) &&
  1324. !_PyUnicode_Equal(modulename, &_Py_ID(__main__))) {
  1325. if (PyFile_WriteObject(modulename, file, Py_PRINT_RAW) < 0) {
  1326. Py_DECREF(modulename);
  1327. return -1;
  1328. }
  1329. Py_DECREF(modulename);
  1330. if (PyFile_WriteString(".", file) < 0) {
  1331. return -1;
  1332. }
  1333. }
  1334. else {
  1335. Py_DECREF(modulename);
  1336. }
  1337. }
  1338. PyObject *qualname = PyType_GetQualName((PyTypeObject *)exc_type);
  1339. if (qualname == NULL || !PyUnicode_Check(qualname)) {
  1340. Py_XDECREF(qualname);
  1341. _PyErr_Clear(tstate);
  1342. if (PyFile_WriteString("<unknown>", file) < 0) {
  1343. return -1;
  1344. }
  1345. }
  1346. else {
  1347. if (PyFile_WriteObject(qualname, file, Py_PRINT_RAW) < 0) {
  1348. Py_DECREF(qualname);
  1349. return -1;
  1350. }
  1351. Py_DECREF(qualname);
  1352. }
  1353. if (exc_value && exc_value != Py_None) {
  1354. if (PyFile_WriteString(": ", file) < 0) {
  1355. return -1;
  1356. }
  1357. if (PyFile_WriteObject(exc_value, file, Py_PRINT_RAW) < 0) {
  1358. _PyErr_Clear(tstate);
  1359. if (PyFile_WriteString("<exception str() failed>", file) < 0) {
  1360. return -1;
  1361. }
  1362. }
  1363. }
  1364. if (PyFile_WriteString("\n", file) < 0) {
  1365. return -1;
  1366. }
  1367. /* Explicitly call file.flush() */
  1368. PyObject *res = _PyObject_CallMethodNoArgs(file, &_Py_ID(flush));
  1369. if (!res) {
  1370. return -1;
  1371. }
  1372. Py_DECREF(res);
  1373. return 0;
  1374. }
  1375. static int
  1376. write_unraisable_exc(PyThreadState *tstate, PyObject *exc_type,
  1377. PyObject *exc_value, PyObject *exc_tb, PyObject *err_msg,
  1378. PyObject *obj)
  1379. {
  1380. PyObject *file = _PySys_GetAttr(tstate, &_Py_ID(stderr));
  1381. if (file == NULL || file == Py_None) {
  1382. return 0;
  1383. }
  1384. /* Hold a strong reference to ensure that sys.stderr doesn't go away
  1385. while we use it */
  1386. Py_INCREF(file);
  1387. int res = write_unraisable_exc_file(tstate, exc_type, exc_value, exc_tb,
  1388. err_msg, obj, file);
  1389. Py_DECREF(file);
  1390. return res;
  1391. }
  1392. PyObject*
  1393. _PyErr_WriteUnraisableDefaultHook(PyObject *args)
  1394. {
  1395. PyThreadState *tstate = _PyThreadState_GET();
  1396. if (!Py_IS_TYPE(args, &UnraisableHookArgsType)) {
  1397. _PyErr_SetString(tstate, PyExc_TypeError,
  1398. "sys.unraisablehook argument type "
  1399. "must be UnraisableHookArgs");
  1400. return NULL;
  1401. }
  1402. /* Borrowed references */
  1403. PyObject *exc_type = PyStructSequence_GET_ITEM(args, 0);
  1404. PyObject *exc_value = PyStructSequence_GET_ITEM(args, 1);
  1405. PyObject *exc_tb = PyStructSequence_GET_ITEM(args, 2);
  1406. PyObject *err_msg = PyStructSequence_GET_ITEM(args, 3);
  1407. PyObject *obj = PyStructSequence_GET_ITEM(args, 4);
  1408. if (write_unraisable_exc(tstate, exc_type, exc_value, exc_tb, err_msg, obj) < 0) {
  1409. return NULL;
  1410. }
  1411. Py_RETURN_NONE;
  1412. }
  1413. /* Call sys.unraisablehook().
  1414. This function can be used when an exception has occurred but there is no way
  1415. for Python to handle it. For example, when a destructor raises an exception
  1416. or during garbage collection (gc.collect()).
  1417. If err_msg_str is non-NULL, the error message is formatted as:
  1418. "Exception ignored %s" % err_msg_str. Otherwise, use "Exception ignored in"
  1419. error message.
  1420. An exception must be set when calling this function. */
  1421. void
  1422. _PyErr_WriteUnraisableMsg(const char *err_msg_str, PyObject *obj)
  1423. {
  1424. PyThreadState *tstate = _PyThreadState_GET();
  1425. _Py_EnsureTstateNotNULL(tstate);
  1426. PyObject *err_msg = NULL;
  1427. PyObject *exc_type, *exc_value, *exc_tb;
  1428. _PyErr_Fetch(tstate, &exc_type, &exc_value, &exc_tb);
  1429. assert(exc_type != NULL);
  1430. if (exc_type == NULL) {
  1431. /* sys.unraisablehook requires that at least exc_type is set */
  1432. goto default_hook;
  1433. }
  1434. if (exc_tb == NULL) {
  1435. PyFrameObject *frame = PyThreadState_GetFrame(tstate);
  1436. if (frame != NULL) {
  1437. exc_tb = _PyTraceBack_FromFrame(NULL, frame);
  1438. if (exc_tb == NULL) {
  1439. _PyErr_Clear(tstate);
  1440. }
  1441. Py_DECREF(frame);
  1442. }
  1443. }
  1444. _PyErr_NormalizeException(tstate, &exc_type, &exc_value, &exc_tb);
  1445. if (exc_tb != NULL && exc_tb != Py_None && PyTraceBack_Check(exc_tb)) {
  1446. if (PyException_SetTraceback(exc_value, exc_tb) < 0) {
  1447. _PyErr_Clear(tstate);
  1448. }
  1449. }
  1450. if (err_msg_str != NULL) {
  1451. err_msg = PyUnicode_FromFormat("Exception ignored %s", err_msg_str);
  1452. if (err_msg == NULL) {
  1453. PyErr_Clear();
  1454. }
  1455. }
  1456. PyObject *hook_args = make_unraisable_hook_args(
  1457. tstate, exc_type, exc_value, exc_tb, err_msg, obj);
  1458. if (hook_args == NULL) {
  1459. err_msg_str = ("Exception ignored on building "
  1460. "sys.unraisablehook arguments");
  1461. goto error;
  1462. }
  1463. PyObject *hook = _PySys_GetAttr(tstate, &_Py_ID(unraisablehook));
  1464. if (hook == NULL) {
  1465. Py_DECREF(hook_args);
  1466. goto default_hook;
  1467. }
  1468. if (_PySys_Audit(tstate, "sys.unraisablehook", "OO", hook, hook_args) < 0) {
  1469. Py_DECREF(hook_args);
  1470. err_msg_str = "Exception ignored in audit hook";
  1471. obj = NULL;
  1472. goto error;
  1473. }
  1474. if (hook == Py_None) {
  1475. Py_DECREF(hook_args);
  1476. goto default_hook;
  1477. }
  1478. PyObject *res = PyObject_CallOneArg(hook, hook_args);
  1479. Py_DECREF(hook_args);
  1480. if (res != NULL) {
  1481. Py_DECREF(res);
  1482. goto done;
  1483. }
  1484. /* sys.unraisablehook failed: log its error using default hook */
  1485. obj = hook;
  1486. err_msg_str = NULL;
  1487. error:
  1488. /* err_msg_str and obj have been updated and we have a new exception */
  1489. Py_XSETREF(err_msg, PyUnicode_FromString(err_msg_str ?
  1490. err_msg_str : "Exception ignored in sys.unraisablehook"));
  1491. Py_XDECREF(exc_type);
  1492. Py_XDECREF(exc_value);
  1493. Py_XDECREF(exc_tb);
  1494. _PyErr_Fetch(tstate, &exc_type, &exc_value, &exc_tb);
  1495. default_hook:
  1496. /* Call the default unraisable hook (ignore failure) */
  1497. (void)write_unraisable_exc(tstate, exc_type, exc_value, exc_tb,
  1498. err_msg, obj);
  1499. done:
  1500. Py_XDECREF(exc_type);
  1501. Py_XDECREF(exc_value);
  1502. Py_XDECREF(exc_tb);
  1503. Py_XDECREF(err_msg);
  1504. _PyErr_Clear(tstate); /* Just in case */
  1505. }
  1506. void
  1507. PyErr_WriteUnraisable(PyObject *obj)
  1508. {
  1509. _PyErr_WriteUnraisableMsg(NULL, obj);
  1510. }
  1511. void
  1512. PyErr_SyntaxLocation(const char *filename, int lineno)
  1513. {
  1514. PyErr_SyntaxLocationEx(filename, lineno, -1);
  1515. }
  1516. /* Set file and line information for the current exception.
  1517. If the exception is not a SyntaxError, also sets additional attributes
  1518. to make printing of exceptions believe it is a syntax error. */
  1519. static void
  1520. PyErr_SyntaxLocationObjectEx(PyObject *filename, int lineno, int col_offset,
  1521. int end_lineno, int end_col_offset)
  1522. {
  1523. PyThreadState *tstate = _PyThreadState_GET();
  1524. /* add attributes for the line number and filename for the error */
  1525. PyObject *exc = _PyErr_GetRaisedException(tstate);
  1526. /* XXX check that it is, indeed, a syntax error. It might not
  1527. * be, though. */
  1528. PyObject *tmp = PyLong_FromLong(lineno);
  1529. if (tmp == NULL) {
  1530. _PyErr_Clear(tstate);
  1531. }
  1532. else {
  1533. if (PyObject_SetAttr(exc, &_Py_ID(lineno), tmp)) {
  1534. _PyErr_Clear(tstate);
  1535. }
  1536. Py_DECREF(tmp);
  1537. }
  1538. tmp = NULL;
  1539. if (col_offset >= 0) {
  1540. tmp = PyLong_FromLong(col_offset);
  1541. if (tmp == NULL) {
  1542. _PyErr_Clear(tstate);
  1543. }
  1544. }
  1545. if (PyObject_SetAttr(exc, &_Py_ID(offset), tmp ? tmp : Py_None)) {
  1546. _PyErr_Clear(tstate);
  1547. }
  1548. Py_XDECREF(tmp);
  1549. tmp = NULL;
  1550. if (end_lineno >= 0) {
  1551. tmp = PyLong_FromLong(end_lineno);
  1552. if (tmp == NULL) {
  1553. _PyErr_Clear(tstate);
  1554. }
  1555. }
  1556. if (PyObject_SetAttr(exc, &_Py_ID(end_lineno), tmp ? tmp : Py_None)) {
  1557. _PyErr_Clear(tstate);
  1558. }
  1559. Py_XDECREF(tmp);
  1560. tmp = NULL;
  1561. if (end_col_offset >= 0) {
  1562. tmp = PyLong_FromLong(end_col_offset);
  1563. if (tmp == NULL) {
  1564. _PyErr_Clear(tstate);
  1565. }
  1566. }
  1567. if (PyObject_SetAttr(exc, &_Py_ID(end_offset), tmp ? tmp : Py_None)) {
  1568. _PyErr_Clear(tstate);
  1569. }
  1570. Py_XDECREF(tmp);
  1571. tmp = NULL;
  1572. if (filename != NULL) {
  1573. if (PyObject_SetAttr(exc, &_Py_ID(filename), filename)) {
  1574. _PyErr_Clear(tstate);
  1575. }
  1576. tmp = PyErr_ProgramTextObject(filename, lineno);
  1577. if (tmp) {
  1578. if (PyObject_SetAttr(exc, &_Py_ID(text), tmp)) {
  1579. _PyErr_Clear(tstate);
  1580. }
  1581. Py_DECREF(tmp);
  1582. }
  1583. else {
  1584. _PyErr_Clear(tstate);
  1585. }
  1586. }
  1587. if ((PyObject *)Py_TYPE(exc) != PyExc_SyntaxError) {
  1588. if (_PyObject_LookupAttr(exc, &_Py_ID(msg), &tmp) < 0) {
  1589. _PyErr_Clear(tstate);
  1590. }
  1591. else if (tmp) {
  1592. Py_DECREF(tmp);
  1593. }
  1594. else {
  1595. tmp = PyObject_Str(exc);
  1596. if (tmp) {
  1597. if (PyObject_SetAttr(exc, &_Py_ID(msg), tmp)) {
  1598. _PyErr_Clear(tstate);
  1599. }
  1600. Py_DECREF(tmp);
  1601. }
  1602. else {
  1603. _PyErr_Clear(tstate);
  1604. }
  1605. }
  1606. if (_PyObject_LookupAttr(exc, &_Py_ID(print_file_and_line), &tmp) < 0) {
  1607. _PyErr_Clear(tstate);
  1608. }
  1609. else if (tmp) {
  1610. Py_DECREF(tmp);
  1611. }
  1612. else {
  1613. if (PyObject_SetAttr(exc, &_Py_ID(print_file_and_line), Py_None)) {
  1614. _PyErr_Clear(tstate);
  1615. }
  1616. }
  1617. }
  1618. _PyErr_SetRaisedException(tstate, exc);
  1619. }
  1620. void
  1621. PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset) {
  1622. PyErr_SyntaxLocationObjectEx(filename, lineno, col_offset, lineno, -1);
  1623. }
  1624. void
  1625. PyErr_RangedSyntaxLocationObject(PyObject *filename, int lineno, int col_offset,
  1626. int end_lineno, int end_col_offset) {
  1627. PyErr_SyntaxLocationObjectEx(filename, lineno, col_offset, end_lineno, end_col_offset);
  1628. }
  1629. void
  1630. PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
  1631. {
  1632. PyThreadState *tstate = _PyThreadState_GET();
  1633. PyObject *fileobj;
  1634. if (filename != NULL) {
  1635. fileobj = PyUnicode_DecodeFSDefault(filename);
  1636. if (fileobj == NULL) {
  1637. _PyErr_Clear(tstate);
  1638. }
  1639. }
  1640. else {
  1641. fileobj = NULL;
  1642. }
  1643. PyErr_SyntaxLocationObject(fileobj, lineno, col_offset);
  1644. Py_XDECREF(fileobj);
  1645. }
  1646. /* Attempt to load the line of text that the exception refers to. If it
  1647. fails, it will return NULL but will not set an exception.
  1648. XXX The functionality of this function is quite similar to the
  1649. functionality in tb_displayline() in traceback.c. */
  1650. static PyObject *
  1651. err_programtext(FILE *fp, int lineno, const char* encoding)
  1652. {
  1653. char linebuf[1000];
  1654. size_t line_size = 0;
  1655. for (int i = 0; i < lineno; ) {
  1656. line_size = 0;
  1657. if (_Py_UniversalNewlineFgetsWithSize(linebuf, sizeof(linebuf),
  1658. fp, NULL, &line_size) == NULL)
  1659. {
  1660. /* Error or EOF. */
  1661. return NULL;
  1662. }
  1663. /* fgets read *something*; if it didn't fill the
  1664. whole buffer, it must have found a newline
  1665. or hit the end of the file; if the last character is \n,
  1666. it obviously found a newline; else we haven't
  1667. yet seen a newline, so must continue */
  1668. if (i + 1 < lineno
  1669. && line_size == sizeof(linebuf) - 1
  1670. && linebuf[sizeof(linebuf) - 2] != '\n')
  1671. {
  1672. continue;
  1673. }
  1674. i++;
  1675. }
  1676. const char *line = linebuf;
  1677. /* Skip BOM. */
  1678. if (lineno == 1 && line_size >= 3 && memcmp(line, "\xef\xbb\xbf", 3) == 0) {
  1679. line += 3;
  1680. line_size -= 3;
  1681. }
  1682. PyObject *res = PyUnicode_Decode(line, line_size, encoding, "replace");
  1683. if (res == NULL) {
  1684. PyErr_Clear();
  1685. }
  1686. return res;
  1687. }
  1688. PyObject *
  1689. PyErr_ProgramText(const char *filename, int lineno)
  1690. {
  1691. if (filename == NULL) {
  1692. return NULL;
  1693. }
  1694. PyObject *filename_obj = PyUnicode_DecodeFSDefault(filename);
  1695. if (filename_obj == NULL) {
  1696. PyErr_Clear();
  1697. return NULL;
  1698. }
  1699. PyObject *res = PyErr_ProgramTextObject(filename_obj, lineno);
  1700. Py_DECREF(filename_obj);
  1701. return res;
  1702. }
  1703. /* Function from Parser/tokenizer/file_tokenizer.c */
  1704. extern char* _PyTokenizer_FindEncodingFilename(int, PyObject *);
  1705. PyObject *
  1706. _PyErr_ProgramDecodedTextObject(PyObject *filename, int lineno, const char* encoding)
  1707. {
  1708. char *found_encoding = NULL;
  1709. if (filename == NULL || lineno <= 0) {
  1710. return NULL;
  1711. }
  1712. FILE *fp = _Py_fopen_obj(filename, "r" PY_STDIOTEXTMODE);
  1713. if (fp == NULL) {
  1714. PyErr_Clear();
  1715. return NULL;
  1716. }
  1717. if (encoding == NULL) {
  1718. int fd = fileno(fp);
  1719. found_encoding = _PyTokenizer_FindEncodingFilename(fd, filename);
  1720. encoding = found_encoding;
  1721. if (encoding == NULL) {
  1722. PyErr_Clear();
  1723. encoding = "utf-8";
  1724. }
  1725. /* Reset position */
  1726. if (lseek(fd, 0, SEEK_SET) == (off_t)-1) {
  1727. fclose(fp);
  1728. PyMem_Free(found_encoding);
  1729. return NULL;
  1730. }
  1731. }
  1732. PyObject *res = err_programtext(fp, lineno, encoding);
  1733. fclose(fp);
  1734. PyMem_Free(found_encoding);
  1735. return res;
  1736. }
  1737. PyObject *
  1738. PyErr_ProgramTextObject(PyObject *filename, int lineno)
  1739. {
  1740. return _PyErr_ProgramDecodedTextObject(filename, lineno, NULL);
  1741. }
  1742. #ifdef __cplusplus
  1743. }
  1744. #endif