/Python/errors.c

http://unladen-swallow.googlecode.com/ · C · 769 lines · 615 code · 76 blank · 78 comment · 148 complexity · dba10598cb1661654db12f7c2e35f4c2 MD5 · raw file

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