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.

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