You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

807 lines
22 KiB

36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
25 years ago
25 years ago
  1. /* Error handling */
  2. #include "Python.h"
  3. #ifndef __STDC__
  4. #ifndef MS_WINDOWS
  5. extern char *strerror(int);
  6. #endif
  7. #endif
  8. #ifdef MS_WINDOWS
  9. #include "windows.h"
  10. #include "winbase.h"
  11. #endif
  12. #include <ctype.h>
  13. #ifdef __cplusplus
  14. extern "C" {
  15. #endif
  16. void
  17. PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
  18. {
  19. PyThreadState *tstate = PyThreadState_GET();
  20. PyObject *oldtype, *oldvalue, *oldtraceback;
  21. if (traceback != NULL && !PyTraceBack_Check(traceback)) {
  22. /* XXX Should never happen -- fatal error instead? */
  23. /* Well, it could be None. */
  24. Py_DECREF(traceback);
  25. traceback = NULL;
  26. }
  27. /* Save these in locals to safeguard against recursive
  28. invocation through Py_XDECREF */
  29. oldtype = tstate->curexc_type;
  30. oldvalue = tstate->curexc_value;
  31. oldtraceback = tstate->curexc_traceback;
  32. tstate->curexc_type = type;
  33. tstate->curexc_value = value;
  34. tstate->curexc_traceback = traceback;
  35. Py_XDECREF(oldtype);
  36. Py_XDECREF(oldvalue);
  37. Py_XDECREF(oldtraceback);
  38. }
  39. void
  40. PyErr_SetObject(PyObject *exception, PyObject *value)
  41. {
  42. Py_XINCREF(exception);
  43. Py_XINCREF(value);
  44. PyErr_Restore(exception, value, (PyObject *)NULL);
  45. }
  46. void
  47. PyErr_SetNone(PyObject *exception)
  48. {
  49. PyErr_SetObject(exception, (PyObject *)NULL);
  50. }
  51. void
  52. PyErr_SetString(PyObject *exception, const char *string)
  53. {
  54. PyObject *value = PyString_FromString(string);
  55. PyErr_SetObject(exception, value);
  56. Py_XDECREF(value);
  57. }
  58. PyObject *
  59. PyErr_Occurred(void)
  60. {
  61. PyThreadState *tstate = PyThreadState_GET();
  62. return tstate->curexc_type;
  63. }
  64. int
  65. PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
  66. {
  67. if (err == NULL || exc == NULL) {
  68. /* maybe caused by "import exceptions" that failed early on */
  69. return 0;
  70. }
  71. if (PyTuple_Check(exc)) {
  72. Py_ssize_t i, n;
  73. n = PyTuple_Size(exc);
  74. for (i = 0; i < n; i++) {
  75. /* Test recursively */
  76. if (PyErr_GivenExceptionMatches(
  77. err, PyTuple_GET_ITEM(exc, i)))
  78. {
  79. return 1;
  80. }
  81. }
  82. return 0;
  83. }
  84. /* err might be an instance, so check its class. */
  85. if (PyExceptionInstance_Check(err))
  86. err = PyExceptionInstance_Class(err);
  87. if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
  88. int res = 0, reclimit;
  89. PyObject *exception, *value, *tb;
  90. PyErr_Fetch(&exception, &value, &tb);
  91. /* Temporarily bump the recursion limit, so that in the most
  92. common case PyObject_IsSubclass will not raise a recursion
  93. error we have to ignore anyway. Don't do it when the limit
  94. is already insanely high, to avoid overflow */
  95. reclimit = Py_GetRecursionLimit();
  96. if (reclimit < (1 << 30))
  97. Py_SetRecursionLimit(reclimit + 5);
  98. res = PyObject_IsSubclass(err, exc);
  99. Py_SetRecursionLimit(reclimit);
  100. /* This function must not fail, so print the error here */
  101. if (res == -1) {
  102. PyErr_WriteUnraisable(err);
  103. res = 0;
  104. }
  105. PyErr_Restore(exception, value, tb);
  106. return res;
  107. }
  108. return err == exc;
  109. }
  110. int
  111. PyErr_ExceptionMatches(PyObject *exc)
  112. {
  113. return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
  114. }
  115. /* Used in many places to normalize a raised exception, including in
  116. eval_code2(), do_raise(), and PyErr_Print()
  117. */
  118. void
  119. PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
  120. {
  121. PyObject *type = *exc;
  122. PyObject *value = *val;
  123. PyObject *inclass = NULL;
  124. PyObject *initial_tb = NULL;
  125. PyThreadState *tstate = NULL;
  126. if (type == NULL) {
  127. /* There was no exception, so nothing to do. */
  128. return;
  129. }
  130. /* If PyErr_SetNone() was used, the value will have been actually
  131. set to NULL.
  132. */
  133. if (!value) {
  134. value = Py_None;
  135. Py_INCREF(value);
  136. }
  137. if (PyExceptionInstance_Check(value))
  138. inclass = PyExceptionInstance_Class(value);
  139. /* Normalize the exception so that if the type is a class, the
  140. value will be an instance.
  141. */
  142. if (PyExceptionClass_Check(type)) {
  143. /* if the value was not an instance, or is not an instance
  144. whose class is (or is derived from) type, then use the
  145. value as an argument to instantiation of the type
  146. class.
  147. */
  148. if (!inclass || !PyObject_IsSubclass(inclass, type)) {
  149. PyObject *args, *res;
  150. if (value == Py_None)
  151. args = PyTuple_New(0);
  152. else if (PyTuple_Check(value)) {
  153. Py_INCREF(value);
  154. args = value;
  155. }
  156. else
  157. args = PyTuple_Pack(1, value);
  158. if (args == NULL)
  159. goto finally;
  160. res = PyEval_CallObject(type, args);
  161. Py_DECREF(args);
  162. if (res == NULL)
  163. goto finally;
  164. Py_DECREF(value);
  165. value = res;
  166. }
  167. /* if the class of the instance doesn't exactly match the
  168. class of the type, believe the instance
  169. */
  170. else if (inclass != type) {
  171. Py_DECREF(type);
  172. type = inclass;
  173. Py_INCREF(type);
  174. }
  175. }
  176. *exc = type;
  177. *val = value;
  178. return;
  179. finally:
  180. Py_DECREF(type);
  181. Py_DECREF(value);
  182. /* If the new exception doesn't set a traceback and the old
  183. exception had a traceback, use the old traceback for the
  184. new exception. It's better than nothing.
  185. */
  186. initial_tb = *tb;
  187. PyErr_Fetch(exc, val, tb);
  188. if (initial_tb != NULL) {
  189. if (*tb == NULL)
  190. *tb = initial_tb;
  191. else
  192. Py_DECREF(initial_tb);
  193. }
  194. /* normalize recursively */
  195. tstate = PyThreadState_GET();
  196. if (++tstate->recursion_depth > Py_GetRecursionLimit()) {
  197. --tstate->recursion_depth;
  198. /* throw away the old exception... */
  199. Py_DECREF(*exc);
  200. Py_DECREF(*val);
  201. /* ... and use the recursion error instead */
  202. *exc = PyExc_RuntimeError;
  203. *val = PyExc_RecursionErrorInst;
  204. Py_INCREF(*exc);
  205. Py_INCREF(*val);
  206. /* just keeping the old traceback */
  207. return;
  208. }
  209. PyErr_NormalizeException(exc, val, tb);
  210. --tstate->recursion_depth;
  211. }
  212. void
  213. PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
  214. {
  215. PyThreadState *tstate = PyThreadState_GET();
  216. *p_type = tstate->curexc_type;
  217. *p_value = tstate->curexc_value;
  218. *p_traceback = tstate->curexc_traceback;
  219. tstate->curexc_type = NULL;
  220. tstate->curexc_value = NULL;
  221. tstate->curexc_traceback = NULL;
  222. }
  223. void
  224. PyErr_Clear(void)
  225. {
  226. PyErr_Restore(NULL, NULL, NULL);
  227. }
  228. /* Convenience functions to set a type error exception and return 0 */
  229. int
  230. PyErr_BadArgument(void)
  231. {
  232. PyErr_SetString(PyExc_TypeError,
  233. "bad argument type for built-in operation");
  234. return 0;
  235. }
  236. PyObject *
  237. PyErr_NoMemory(void)
  238. {
  239. if (PyErr_ExceptionMatches(PyExc_MemoryError))
  240. /* already current */
  241. return NULL;
  242. /* raise the pre-allocated instance if it still exists */
  243. if (PyExc_MemoryErrorInst)
  244. PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst);
  245. else
  246. /* this will probably fail since there's no memory and hee,
  247. hee, we have to instantiate this class
  248. */
  249. PyErr_SetNone(PyExc_MemoryError);
  250. return NULL;
  251. }
  252. PyObject *
  253. PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
  254. {
  255. PyObject *v;
  256. char *s;
  257. int i = errno;
  258. #ifdef PLAN9
  259. char errbuf[ERRMAX];
  260. #endif
  261. #ifdef MS_WINDOWS
  262. char *s_buf = NULL;
  263. char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
  264. #endif
  265. #ifdef EINTR
  266. if (i == EINTR && PyErr_CheckSignals())
  267. return NULL;
  268. #endif
  269. #ifdef PLAN9
  270. rerrstr(errbuf, sizeof errbuf);
  271. s = errbuf;
  272. #else
  273. if (i == 0)
  274. s = "Error"; /* Sometimes errno didn't get set */
  275. else
  276. #ifndef MS_WINDOWS
  277. s = strerror(i);
  278. #else
  279. {
  280. /* Note that the Win32 errors do not lineup with the
  281. errno error. So if the error is in the MSVC error
  282. table, we use it, otherwise we assume it really _is_
  283. a Win32 error code
  284. */
  285. if (i > 0 && i < _sys_nerr) {
  286. s = _sys_errlist[i];
  287. }
  288. else {
  289. int len = FormatMessage(
  290. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  291. FORMAT_MESSAGE_FROM_SYSTEM |
  292. FORMAT_MESSAGE_IGNORE_INSERTS,
  293. NULL, /* no message source */
  294. i,
  295. MAKELANGID(LANG_NEUTRAL,
  296. SUBLANG_DEFAULT),
  297. /* Default language */
  298. (LPTSTR) &s_buf,
  299. 0, /* size not used */
  300. NULL); /* no args */
  301. if (len==0) {
  302. /* Only ever seen this in out-of-mem
  303. situations */
  304. sprintf(s_small_buf, "Windows Error 0x%X", i);
  305. s = s_small_buf;
  306. s_buf = NULL;
  307. } else {
  308. s = s_buf;
  309. /* remove trailing cr/lf and dots */
  310. while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
  311. s[--len] = '\0';
  312. }
  313. }
  314. }
  315. #endif /* Unix/Windows */
  316. #endif /* PLAN 9*/
  317. if (filenameObject != NULL)
  318. v = Py_BuildValue("(isO)", i, s, filenameObject);
  319. else
  320. v = Py_BuildValue("(is)", i, s);
  321. if (v != NULL) {
  322. PyErr_SetObject(exc, v);
  323. Py_DECREF(v);
  324. }
  325. #ifdef MS_WINDOWS
  326. LocalFree(s_buf);
  327. #endif
  328. return NULL;
  329. }
  330. PyObject *
  331. PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
  332. {
  333. PyObject *name = filename ? PyString_FromString(filename) : NULL;
  334. PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
  335. Py_XDECREF(name);
  336. return result;
  337. }
  338. #ifdef MS_WINDOWS
  339. PyObject *
  340. PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename)
  341. {
  342. PyObject *name = filename ?
  343. PyUnicode_FromUnicode(filename, wcslen(filename)) :
  344. NULL;
  345. PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
  346. Py_XDECREF(name);
  347. return result;
  348. }
  349. #endif /* MS_WINDOWS */
  350. PyObject *
  351. PyErr_SetFromErrno(PyObject *exc)
  352. {
  353. return PyErr_SetFromErrnoWithFilenameObject(exc, NULL);
  354. }
  355. #ifdef MS_WINDOWS
  356. /* Windows specific error code handling */
  357. PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
  358. PyObject *exc,
  359. int ierr,
  360. PyObject *filenameObject)
  361. {
  362. int len;
  363. char *s;
  364. char *s_buf = NULL; /* Free via LocalFree */
  365. char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
  366. PyObject *v;
  367. DWORD err = (DWORD)ierr;
  368. if (err==0) err = GetLastError();
  369. len = FormatMessage(
  370. /* Error API error */
  371. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  372. FORMAT_MESSAGE_FROM_SYSTEM |
  373. FORMAT_MESSAGE_IGNORE_INSERTS,
  374. NULL, /* no message source */
  375. err,
  376. MAKELANGID(LANG_NEUTRAL,
  377. SUBLANG_DEFAULT), /* Default language */
  378. (LPTSTR) &s_buf,
  379. 0, /* size not used */
  380. NULL); /* no args */
  381. if (len==0) {
  382. /* Only seen this in out of mem situations */
  383. sprintf(s_small_buf, "Windows Error 0x%X", err);
  384. s = s_small_buf;
  385. s_buf = NULL;
  386. } else {
  387. s = s_buf;
  388. /* remove trailing cr/lf and dots */
  389. while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
  390. s[--len] = '\0';
  391. }
  392. if (filenameObject != NULL)
  393. v = Py_BuildValue("(isO)", err, s, filenameObject);
  394. else
  395. v = Py_BuildValue("(is)", err, s);
  396. if (v != NULL) {
  397. PyErr_SetObject(exc, v);
  398. Py_DECREF(v);
  399. }
  400. LocalFree(s_buf);
  401. return NULL;
  402. }
  403. PyObject *PyErr_SetExcFromWindowsErrWithFilename(
  404. PyObject *exc,
  405. int ierr,
  406. const char *filename)
  407. {
  408. PyObject *name = filename ? PyString_FromString(filename) : NULL;
  409. PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
  410. ierr,
  411. name);
  412. Py_XDECREF(name);
  413. return ret;
  414. }
  415. PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
  416. PyObject *exc,
  417. int ierr,
  418. const Py_UNICODE *filename)
  419. {
  420. PyObject *name = filename ?
  421. PyUnicode_FromUnicode(filename, wcslen(filename)) :
  422. NULL;
  423. PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
  424. ierr,
  425. name);
  426. Py_XDECREF(name);
  427. return ret;
  428. }
  429. PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
  430. {
  431. return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
  432. }
  433. PyObject *PyErr_SetFromWindowsErr(int ierr)
  434. {
  435. return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError,
  436. ierr, NULL);
  437. }
  438. PyObject *PyErr_SetFromWindowsErrWithFilename(
  439. int ierr,
  440. const char *filename)
  441. {
  442. PyObject *name = filename ? PyString_FromString(filename) : NULL;
  443. PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
  444. PyExc_WindowsError,
  445. ierr, name);
  446. Py_XDECREF(name);
  447. return result;
  448. }
  449. PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
  450. int ierr,
  451. const Py_UNICODE *filename)
  452. {
  453. PyObject *name = filename ?
  454. PyUnicode_FromUnicode(filename, wcslen(filename)) :
  455. NULL;
  456. PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
  457. PyExc_WindowsError,
  458. ierr, name);
  459. Py_XDECREF(name);
  460. return result;
  461. }
  462. #endif /* MS_WINDOWS */
  463. void
  464. _PyErr_BadInternalCall(char *filename, int lineno)
  465. {
  466. PyErr_Format(PyExc_SystemError,
  467. "%s:%d: bad argument to internal function",
  468. filename, lineno);
  469. }
  470. /* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
  471. export the entry point for existing object code: */
  472. #undef PyErr_BadInternalCall
  473. void
  474. PyErr_BadInternalCall(void)
  475. {
  476. PyErr_Format(PyExc_SystemError,
  477. "bad argument to internal function");
  478. }
  479. #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
  480. PyObject *
  481. PyErr_Format(PyObject *exception, const char *format, ...)
  482. {
  483. va_list vargs;
  484. PyObject* string;
  485. #ifdef HAVE_STDARG_PROTOTYPES
  486. va_start(vargs, format);
  487. #else
  488. va_start(vargs);
  489. #endif
  490. string = PyString_FromFormatV(format, vargs);
  491. PyErr_SetObject(exception, string);
  492. Py_XDECREF(string);
  493. va_end(vargs);
  494. return NULL;
  495. }
  496. PyObject *
  497. PyErr_NewException(char *name, PyObject *base, PyObject *dict)
  498. {
  499. char *dot;
  500. PyObject *modulename = NULL;
  501. PyObject *classname = NULL;
  502. PyObject *mydict = NULL;
  503. PyObject *bases = NULL;
  504. PyObject *result = NULL;
  505. dot = strrchr(name, '.');
  506. if (dot == NULL) {
  507. PyErr_SetString(PyExc_SystemError,
  508. "PyErr_NewException: name must be module.class");
  509. return NULL;
  510. }
  511. if (base == NULL)
  512. base = PyExc_Exception;
  513. if (dict == NULL) {
  514. dict = mydict = PyDict_New();
  515. if (dict == NULL)
  516. goto failure;
  517. }
  518. if (PyDict_GetItemString(dict, "__module__") == NULL) {
  519. modulename = PyString_FromStringAndSize(name,
  520. (Py_ssize_t)(dot-name));
  521. if (modulename == NULL)
  522. goto failure;
  523. if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
  524. goto failure;
  525. }
  526. if (PyTuple_Check(base)) {
  527. bases = base;
  528. /* INCREF as we create a new ref in the else branch */
  529. Py_INCREF(bases);
  530. } else {
  531. bases = PyTuple_Pack(1, base);
  532. if (bases == NULL)
  533. goto failure;
  534. }
  535. /* Create a real new-style class. */
  536. result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
  537. dot+1, bases, dict);
  538. failure:
  539. Py_XDECREF(bases);
  540. Py_XDECREF(mydict);
  541. Py_XDECREF(classname);
  542. Py_XDECREF(modulename);
  543. return result;
  544. }
  545. /* Create an exception with docstring */
  546. PyObject *
  547. PyErr_NewExceptionWithDoc(char *name, char *doc, PyObject *base, PyObject *dict)
  548. {
  549. int result;
  550. PyObject *ret = NULL;
  551. PyObject *mydict = NULL; /* points to the dict only if we create it */
  552. PyObject *docobj;
  553. if (dict == NULL) {
  554. dict = mydict = PyDict_New();
  555. if (dict == NULL) {
  556. return NULL;
  557. }
  558. }
  559. if (doc != NULL) {
  560. docobj = PyString_FromString(doc);
  561. if (docobj == NULL)
  562. goto failure;
  563. result = PyDict_SetItemString(dict, "__doc__", docobj);
  564. Py_DECREF(docobj);
  565. if (result < 0)
  566. goto failure;
  567. }
  568. ret = PyErr_NewException(name, base, dict);
  569. failure:
  570. Py_XDECREF(mydict);
  571. return ret;
  572. }
  573. /* Call when an exception has occurred but there is no way for Python
  574. to handle it. Examples: exception in __del__ or during GC. */
  575. void
  576. PyErr_WriteUnraisable(PyObject *obj)
  577. {
  578. PyObject *f, *t, *v, *tb;
  579. PyErr_Fetch(&t, &v, &tb);
  580. f = PySys_GetObject("stderr");
  581. if (f != NULL) {
  582. PyFile_WriteString("Exception ", f);
  583. if (t) {
  584. PyObject* moduleName;
  585. char* className;
  586. assert(PyExceptionClass_Check(t));
  587. className = PyExceptionClass_Name(t);
  588. if (className != NULL) {
  589. char *dot = strrchr(className, '.');
  590. if (dot != NULL)
  591. className = dot+1;
  592. }
  593. moduleName = PyObject_GetAttrString(t, "__module__");
  594. if (moduleName == NULL)
  595. PyFile_WriteString("<unknown>", f);
  596. else {
  597. char* modstr = PyString_AsString(moduleName);
  598. if (modstr &&
  599. strcmp(modstr, "exceptions") != 0)
  600. {
  601. PyFile_WriteString(modstr, f);
  602. PyFile_WriteString(".", f);
  603. }
  604. }
  605. if (className == NULL)
  606. PyFile_WriteString("<unknown>", f);
  607. else
  608. PyFile_WriteString(className, f);
  609. if (v && v != Py_None) {
  610. PyFile_WriteString(": ", f);
  611. PyFile_WriteObject(v, f, 0);
  612. }
  613. Py_XDECREF(moduleName);
  614. }
  615. PyFile_WriteString(" in ", f);
  616. PyFile_WriteObject(obj, f, 0);
  617. PyFile_WriteString(" ignored\n", f);
  618. PyErr_Clear(); /* Just in case */
  619. }
  620. Py_XDECREF(t);
  621. Py_XDECREF(v);
  622. Py_XDECREF(tb);
  623. }
  624. extern PyObject *PyModule_GetWarningsModule(void);
  625. /* Set file and line information for the current exception.
  626. If the exception is not a SyntaxError, also sets additional attributes
  627. to make printing of exceptions believe it is a syntax error. */
  628. void
  629. PyErr_SyntaxLocation(const char *filename, int lineno)
  630. {
  631. PyObject *exc, *v, *tb, *tmp;
  632. /* add attributes for the line number and filename for the error */
  633. PyErr_Fetch(&exc, &v, &tb);
  634. PyErr_NormalizeException(&exc, &v, &tb);
  635. /* XXX check that it is, indeed, a syntax error. It might not
  636. * be, though. */
  637. tmp = PyInt_FromLong(lineno);
  638. if (tmp == NULL)
  639. PyErr_Clear();
  640. else {
  641. if (PyObject_SetAttrString(v, "lineno", tmp))
  642. PyErr_Clear();
  643. Py_DECREF(tmp);
  644. }
  645. if (filename != NULL) {
  646. tmp = PyString_FromString(filename);
  647. if (tmp == NULL)
  648. PyErr_Clear();
  649. else {
  650. if (PyObject_SetAttrString(v, "filename", tmp))
  651. PyErr_Clear();
  652. Py_DECREF(tmp);
  653. }
  654. tmp = PyErr_ProgramText(filename, lineno);
  655. if (tmp) {
  656. if (PyObject_SetAttrString(v, "text", tmp))
  657. PyErr_Clear();
  658. Py_DECREF(tmp);
  659. }
  660. }
  661. if (PyObject_SetAttrString(v, "offset", Py_None)) {
  662. PyErr_Clear();
  663. }
  664. if (exc != PyExc_SyntaxError) {
  665. if (!PyObject_HasAttrString(v, "msg")) {
  666. tmp = PyObject_Str(v);
  667. if (tmp) {
  668. if (PyObject_SetAttrString(v, "msg", tmp))
  669. PyErr_Clear();
  670. Py_DECREF(tmp);
  671. } else {
  672. PyErr_Clear();
  673. }
  674. }
  675. if (!PyObject_HasAttrString(v, "print_file_and_line")) {
  676. if (PyObject_SetAttrString(v, "print_file_and_line",
  677. Py_None))
  678. PyErr_Clear();
  679. }
  680. }
  681. PyErr_Restore(exc, v, tb);
  682. }
  683. /* com_fetch_program_text will attempt to load the line of text that
  684. the exception refers to. If it fails, it will return NULL but will
  685. not set an exception.
  686. XXX The functionality of this function is quite similar to the
  687. functionality in tb_displayline() in traceback.c.
  688. */
  689. PyObject *
  690. PyErr_ProgramText(const char *filename, int lineno)
  691. {
  692. FILE *fp;
  693. int i;
  694. char linebuf[1000];
  695. if (filename == NULL || *filename == '\0' || lineno <= 0)
  696. return NULL;
  697. fp = fopen(filename, "r" PY_STDIOTEXTMODE);
  698. if (fp == NULL)
  699. return NULL;
  700. for (i = 0; i < lineno; i++) {
  701. char *pLastChar = &linebuf[sizeof(linebuf) - 2];
  702. do {
  703. *pLastChar = '\0';
  704. if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf, fp, NULL) == NULL)
  705. break;
  706. /* fgets read *something*; if it didn't get as
  707. far as pLastChar, it must have found a newline
  708. or hit the end of the file; if pLastChar is \n,
  709. it obviously found a newline; else we haven't
  710. yet seen a newline, so must continue */
  711. } while (*pLastChar != '\0' && *pLastChar != '\n');
  712. }
  713. fclose(fp);
  714. if (i == lineno) {
  715. char *p = linebuf;
  716. while (*p == ' ' || *p == '\t' || *p == '\014')
  717. p++;
  718. return PyString_FromString(p);
  719. }
  720. return NULL;
  721. }
  722. #ifdef __cplusplus
  723. }
  724. #endif