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.

2882 lines
86 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
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
  1. /* File object implementation */
  2. #define PY_SSIZE_T_CLEAN
  3. #include "Python.h"
  4. #include "structmember.h"
  5. #ifdef HAVE_SYS_TYPES_H
  6. #include <sys/types.h>
  7. #endif /* HAVE_SYS_TYPES_H */
  8. #ifdef MS_WINDOWS
  9. #define fileno _fileno
  10. /* can simulate truncate with Win32 API functions; see file_truncate */
  11. #define HAVE_FTRUNCATE
  12. #define WIN32_LEAN_AND_MEAN
  13. #include <windows.h>
  14. #endif
  15. #if defined(PYOS_OS2) && defined(PYCC_GCC)
  16. #include <io.h>
  17. #endif
  18. #define BUF(v) PyString_AS_STRING((PyStringObject *)v)
  19. #ifdef HAVE_ERRNO_H
  20. #include <errno.h>
  21. #endif
  22. #ifdef HAVE_GETC_UNLOCKED
  23. #define GETC(f) getc_unlocked(f)
  24. #define FLOCKFILE(f) flockfile(f)
  25. #define FUNLOCKFILE(f) funlockfile(f)
  26. #else
  27. #define GETC(f) getc(f)
  28. #define FLOCKFILE(f)
  29. #define FUNLOCKFILE(f)
  30. #endif
  31. /* Bits in f_newlinetypes */
  32. #define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
  33. #define NEWLINE_CR 1 /* \r newline seen */
  34. #define NEWLINE_LF 2 /* \n newline seen */
  35. #define NEWLINE_CRLF 4 /* \r\n newline seen */
  36. /*
  37. * These macros release the GIL while preventing the f_close() function being
  38. * called in the interval between them. For that purpose, a running total of
  39. * the number of currently running unlocked code sections is kept in
  40. * the unlocked_count field of the PyFileObject. The close() method raises
  41. * an IOError if that field is non-zero. See issue #815646, #595601.
  42. */
  43. #define FILE_BEGIN_ALLOW_THREADS(fobj) \
  44. { \
  45. fobj->unlocked_count++; \
  46. Py_BEGIN_ALLOW_THREADS
  47. #define FILE_END_ALLOW_THREADS(fobj) \
  48. Py_END_ALLOW_THREADS \
  49. fobj->unlocked_count--; \
  50. assert(fobj->unlocked_count >= 0); \
  51. }
  52. #define FILE_ABORT_ALLOW_THREADS(fobj) \
  53. Py_BLOCK_THREADS \
  54. fobj->unlocked_count--; \
  55. assert(fobj->unlocked_count >= 0);
  56. #ifdef __cplusplus
  57. extern "C" {
  58. #endif
  59. FILE *
  60. PyFile_AsFile(PyObject *f)
  61. {
  62. if (f == NULL || !PyFile_Check(f))
  63. return NULL;
  64. else
  65. return ((PyFileObject *)f)->f_fp;
  66. }
  67. void PyFile_IncUseCount(PyFileObject *fobj)
  68. {
  69. fobj->unlocked_count++;
  70. }
  71. void PyFile_DecUseCount(PyFileObject *fobj)
  72. {
  73. fobj->unlocked_count--;
  74. assert(fobj->unlocked_count >= 0);
  75. }
  76. PyObject *
  77. PyFile_Name(PyObject *f)
  78. {
  79. if (f == NULL || !PyFile_Check(f))
  80. return NULL;
  81. else
  82. return ((PyFileObject *)f)->f_name;
  83. }
  84. /* This is a safe wrapper around PyObject_Print to print to the FILE
  85. of a PyFileObject. PyObject_Print releases the GIL but knows nothing
  86. about PyFileObject. */
  87. static int
  88. file_PyObject_Print(PyObject *op, PyFileObject *f, int flags)
  89. {
  90. int result;
  91. PyFile_IncUseCount(f);
  92. result = PyObject_Print(op, f->f_fp, flags);
  93. PyFile_DecUseCount(f);
  94. return result;
  95. }
  96. /* On Unix, fopen will succeed for directories.
  97. In Python, there should be no file objects referring to
  98. directories, so we need a check. */
  99. static PyFileObject*
  100. dircheck(PyFileObject* f)
  101. {
  102. #if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
  103. struct stat buf;
  104. if (f->f_fp == NULL)
  105. return f;
  106. if (fstat(fileno(f->f_fp), &buf) == 0 &&
  107. S_ISDIR(buf.st_mode)) {
  108. char *msg = strerror(EISDIR);
  109. PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(isO)",
  110. EISDIR, msg, f->f_name);
  111. PyErr_SetObject(PyExc_IOError, exc);
  112. Py_XDECREF(exc);
  113. return NULL;
  114. }
  115. #endif
  116. return f;
  117. }
  118. static PyObject *
  119. fill_file_fields(PyFileObject *f, FILE *fp, PyObject *name, char *mode,
  120. int (*close)(FILE *))
  121. {
  122. assert(name != NULL);
  123. assert(f != NULL);
  124. assert(PyFile_Check(f));
  125. assert(f->f_fp == NULL);
  126. Py_DECREF(f->f_name);
  127. Py_DECREF(f->f_mode);
  128. Py_DECREF(f->f_encoding);
  129. Py_DECREF(f->f_errors);
  130. Py_INCREF(name);
  131. f->f_name = name;
  132. f->f_mode = PyString_FromString(mode);
  133. f->f_close = close;
  134. f->f_softspace = 0;
  135. f->f_binary = strchr(mode,'b') != NULL;
  136. f->f_buf = NULL;
  137. f->f_univ_newline = (strchr(mode, 'U') != NULL);
  138. f->f_newlinetypes = NEWLINE_UNKNOWN;
  139. f->f_skipnextlf = 0;
  140. Py_INCREF(Py_None);
  141. f->f_encoding = Py_None;
  142. Py_INCREF(Py_None);
  143. f->f_errors = Py_None;
  144. f->readable = f->writable = 0;
  145. if (strchr(mode, 'r') != NULL || f->f_univ_newline)
  146. f->readable = 1;
  147. if (strchr(mode, 'w') != NULL || strchr(mode, 'a') != NULL)
  148. f->writable = 1;
  149. if (strchr(mode, '+') != NULL)
  150. f->readable = f->writable = 1;
  151. if (f->f_mode == NULL)
  152. return NULL;
  153. f->f_fp = fp;
  154. f = dircheck(f);
  155. return (PyObject *) f;
  156. }
  157. #if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
  158. #define Py_VERIFY_WINNT
  159. /* The CRT on windows compiled with Visual Studio 2005 and higher may
  160. * assert if given invalid mode strings. This is all fine and well
  161. * in static languages like C where the mode string is typcially hard
  162. * coded. But in Python, were we pass in the mode string from the user,
  163. * we need to verify it first manually
  164. */
  165. static int _PyVerify_Mode_WINNT(const char *mode)
  166. {
  167. /* See if mode string is valid on Windows to avoid hard assertions */
  168. /* remove leading spacese */
  169. int singles = 0;
  170. int pairs = 0;
  171. int encoding = 0;
  172. const char *s, *c;
  173. while(*mode == ' ') /* strip initial spaces */
  174. ++mode;
  175. if (!strchr("rwa", *mode)) /* must start with one of these */
  176. return 0;
  177. while (*++mode) {
  178. if (*mode == ' ' || *mode == 'N') /* ignore spaces and N */
  179. continue;
  180. s = "+TD"; /* each of this can appear only once */
  181. c = strchr(s, *mode);
  182. if (c) {
  183. ptrdiff_t idx = s-c;
  184. if (singles & (1<<idx))
  185. return 0;
  186. singles |= (1<<idx);
  187. continue;
  188. }
  189. s = "btcnSR"; /* only one of each letter in the pairs allowed */
  190. c = strchr(s, *mode);
  191. if (c) {
  192. ptrdiff_t idx = (s-c)/2;
  193. if (pairs & (1<<idx))
  194. return 0;
  195. pairs |= (1<<idx);
  196. continue;
  197. }
  198. if (*mode == ',') {
  199. encoding = 1;
  200. break;
  201. }
  202. return 0; /* found an invalid char */
  203. }
  204. if (encoding) {
  205. char *e[] = {"UTF-8", "UTF-16LE", "UNICODE"};
  206. while (*mode == ' ')
  207. ++mode;
  208. /* find 'ccs =' */
  209. if (strncmp(mode, "ccs", 3))
  210. return 0;
  211. mode += 3;
  212. while (*mode == ' ')
  213. ++mode;
  214. if (*mode != '=')
  215. return 0;
  216. while (*mode == ' ')
  217. ++mode;
  218. for(encoding = 0; encoding<_countof(e); ++encoding) {
  219. size_t l = strlen(e[encoding]);
  220. if (!strncmp(mode, e[encoding], l)) {
  221. mode += l; /* found a valid encoding */
  222. break;
  223. }
  224. }
  225. if (encoding == _countof(e))
  226. return 0;
  227. }
  228. /* skip trailing spaces */
  229. while (*mode == ' ')
  230. ++mode;
  231. return *mode == '\0'; /* must be at the end of the string */
  232. }
  233. #endif
  234. /* check for known incorrect mode strings - problem is, platforms are
  235. free to accept any mode characters they like and are supposed to
  236. ignore stuff they don't understand... write or append mode with
  237. universal newline support is expressly forbidden by PEP 278.
  238. Additionally, remove the 'U' from the mode string as platforms
  239. won't know what it is. Non-zero return signals an exception */
  240. int
  241. _PyFile_SanitizeMode(char *mode)
  242. {
  243. char *upos;
  244. size_t len = strlen(mode);
  245. if (!len) {
  246. PyErr_SetString(PyExc_ValueError, "empty mode string");
  247. return -1;
  248. }
  249. upos = strchr(mode, 'U');
  250. if (upos) {
  251. memmove(upos, upos+1, len-(upos-mode)); /* incl null char */
  252. if (mode[0] == 'w' || mode[0] == 'a') {
  253. PyErr_Format(PyExc_ValueError, "universal newline "
  254. "mode can only be used with modes "
  255. "starting with 'r'");
  256. return -1;
  257. }
  258. if (mode[0] != 'r') {
  259. memmove(mode+1, mode, strlen(mode)+1);
  260. mode[0] = 'r';
  261. }
  262. if (!strchr(mode, 'b')) {
  263. memmove(mode+2, mode+1, strlen(mode));
  264. mode[1] = 'b';
  265. }
  266. } else if (mode[0] != 'r' && mode[0] != 'w' && mode[0] != 'a') {
  267. PyErr_Format(PyExc_ValueError, "mode string must begin with "
  268. "one of 'r', 'w', 'a' or 'U', not '%.200s'", mode);
  269. return -1;
  270. }
  271. #ifdef Py_VERIFY_WINNT
  272. /* additional checks on NT with visual studio 2005 and higher */
  273. if (!_PyVerify_Mode_WINNT(mode)) {
  274. PyErr_Format(PyExc_ValueError, "Invalid mode ('%.50s')", mode);
  275. return -1;
  276. }
  277. #endif
  278. return 0;
  279. }
  280. static PyObject *
  281. open_the_file(PyFileObject *f, char *name, char *mode)
  282. {
  283. char *newmode;
  284. assert(f != NULL);
  285. assert(PyFile_Check(f));
  286. #ifdef MS_WINDOWS
  287. /* windows ignores the passed name in order to support Unicode */
  288. assert(f->f_name != NULL);
  289. #else
  290. assert(name != NULL);
  291. #endif
  292. assert(mode != NULL);
  293. assert(f->f_fp == NULL);
  294. /* probably need to replace 'U' by 'rb' */
  295. newmode = PyMem_MALLOC(strlen(mode) + 3);
  296. if (!newmode) {
  297. PyErr_NoMemory();
  298. return NULL;
  299. }
  300. strcpy(newmode, mode);
  301. if (_PyFile_SanitizeMode(newmode)) {
  302. f = NULL;
  303. goto cleanup;
  304. }
  305. /* rexec.py can't stop a user from getting the file() constructor --
  306. all they have to do is get *any* file object f, and then do
  307. type(f). Here we prevent them from doing damage with it. */
  308. if (PyEval_GetRestricted()) {
  309. PyErr_SetString(PyExc_IOError,
  310. "file() constructor not accessible in restricted mode");
  311. f = NULL;
  312. goto cleanup;
  313. }
  314. errno = 0;
  315. #ifdef MS_WINDOWS
  316. if (PyUnicode_Check(f->f_name)) {
  317. PyObject *wmode;
  318. wmode = PyUnicode_DecodeASCII(newmode, strlen(newmode), NULL);
  319. if (f->f_name && wmode) {
  320. FILE_BEGIN_ALLOW_THREADS(f)
  321. /* PyUnicode_AS_UNICODE OK without thread
  322. lock as it is a simple dereference. */
  323. f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
  324. PyUnicode_AS_UNICODE(wmode));
  325. FILE_END_ALLOW_THREADS(f)
  326. }
  327. Py_XDECREF(wmode);
  328. }
  329. #endif
  330. if (NULL == f->f_fp && NULL != name) {
  331. FILE_BEGIN_ALLOW_THREADS(f)
  332. f->f_fp = fopen(name, newmode);
  333. FILE_END_ALLOW_THREADS(f)
  334. }
  335. if (f->f_fp == NULL) {
  336. #if defined _MSC_VER && (_MSC_VER < 1400 || !defined(__STDC_SECURE_LIB__))
  337. /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
  338. * across all Windows flavors. When it sets EINVAL varies
  339. * across Windows flavors, the exact conditions aren't
  340. * documented, and the answer lies in the OS's implementation
  341. * of Win32's CreateFile function (whose source is secret).
  342. * Seems the best we can do is map EINVAL to ENOENT.
  343. * Starting with Visual Studio .NET 2005, EINVAL is correctly
  344. * set by our CRT error handler (set in exceptions.c.)
  345. */
  346. if (errno == 0) /* bad mode string */
  347. errno = EINVAL;
  348. else if (errno == EINVAL) /* unknown, but not a mode string */
  349. errno = ENOENT;
  350. #endif
  351. /* EINVAL is returned when an invalid filename or
  352. * an invalid mode is supplied. */
  353. if (errno == EINVAL) {
  354. PyObject *v;
  355. char message[100];
  356. PyOS_snprintf(message, 100,
  357. "invalid mode ('%.50s') or filename", mode);
  358. v = Py_BuildValue("(isO)", errno, message, f->f_name);
  359. if (v != NULL) {
  360. PyErr_SetObject(PyExc_IOError, v);
  361. Py_DECREF(v);
  362. }
  363. }
  364. else
  365. PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
  366. f = NULL;
  367. }
  368. if (f != NULL)
  369. f = dircheck(f);
  370. cleanup:
  371. PyMem_FREE(newmode);
  372. return (PyObject *)f;
  373. }
  374. static PyObject *
  375. close_the_file(PyFileObject *f)
  376. {
  377. int sts = 0;
  378. int (*local_close)(FILE *);
  379. FILE *local_fp = f->f_fp;
  380. char *local_setbuf = f->f_setbuf;
  381. if (local_fp != NULL) {
  382. local_close = f->f_close;
  383. if (local_close != NULL && f->unlocked_count > 0) {
  384. if (f->ob_refcnt > 0) {
  385. PyErr_SetString(PyExc_IOError,
  386. "close() called during concurrent "
  387. "operation on the same file object.");
  388. } else {
  389. /* This should not happen unless someone is
  390. * carelessly playing with the PyFileObject
  391. * struct fields and/or its associated FILE
  392. * pointer. */
  393. PyErr_SetString(PyExc_SystemError,
  394. "PyFileObject locking error in "
  395. "destructor (refcnt <= 0 at close).");
  396. }
  397. return NULL;
  398. }
  399. /* NULL out the FILE pointer before releasing the GIL, because
  400. * it will not be valid anymore after the close() function is
  401. * called. */
  402. f->f_fp = NULL;
  403. if (local_close != NULL) {
  404. /* Issue #9295: must temporarily reset f_setbuf so that another
  405. thread doesn't free it when running file_close() concurrently.
  406. Otherwise this close() will crash when flushing the buffer. */
  407. f->f_setbuf = NULL;
  408. Py_BEGIN_ALLOW_THREADS
  409. errno = 0;
  410. sts = (*local_close)(local_fp);
  411. Py_END_ALLOW_THREADS
  412. f->f_setbuf = local_setbuf;
  413. if (sts == EOF)
  414. return PyErr_SetFromErrno(PyExc_IOError);
  415. if (sts != 0)
  416. return PyInt_FromLong((long)sts);
  417. }
  418. }
  419. Py_RETURN_NONE;
  420. }
  421. PyObject *
  422. PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
  423. {
  424. PyFileObject *f;
  425. PyObject *o_name;
  426. f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type, NULL, NULL);
  427. if (f == NULL)
  428. return NULL;
  429. o_name = PyString_FromString(name);
  430. if (o_name == NULL) {
  431. if (close != NULL && fp != NULL)
  432. close(fp);
  433. Py_DECREF(f);
  434. return NULL;
  435. }
  436. if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
  437. Py_DECREF(f);
  438. Py_DECREF(o_name);
  439. return NULL;
  440. }
  441. Py_DECREF(o_name);
  442. return (PyObject *)f;
  443. }
  444. PyObject *
  445. PyFile_FromString(char *name, char *mode)
  446. {
  447. extern int fclose(FILE *);
  448. PyFileObject *f;
  449. f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
  450. if (f != NULL) {
  451. if (open_the_file(f, name, mode) == NULL) {
  452. Py_DECREF(f);
  453. f = NULL;
  454. }
  455. }
  456. return (PyObject *)f;
  457. }
  458. void
  459. PyFile_SetBufSize(PyObject *f, int bufsize)
  460. {
  461. PyFileObject *file = (PyFileObject *)f;
  462. if (bufsize >= 0) {
  463. int type;
  464. switch (bufsize) {
  465. case 0:
  466. type = _IONBF;
  467. break;
  468. #ifdef HAVE_SETVBUF
  469. case 1:
  470. type = _IOLBF;
  471. bufsize = BUFSIZ;
  472. break;
  473. #endif
  474. default:
  475. type = _IOFBF;
  476. #ifndef HAVE_SETVBUF
  477. bufsize = BUFSIZ;
  478. #endif
  479. break;
  480. }
  481. fflush(file->f_fp);
  482. if (type == _IONBF) {
  483. PyMem_Free(file->f_setbuf);
  484. file->f_setbuf = NULL;
  485. } else {
  486. file->f_setbuf = (char *)PyMem_Realloc(file->f_setbuf,
  487. bufsize);
  488. }
  489. #ifdef HAVE_SETVBUF
  490. setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
  491. #else /* !HAVE_SETVBUF */
  492. setbuf(file->f_fp, file->f_setbuf);
  493. #endif /* !HAVE_SETVBUF */
  494. }
  495. }
  496. /* Set the encoding used to output Unicode strings.
  497. Return 1 on success, 0 on failure. */
  498. int
  499. PyFile_SetEncoding(PyObject *f, const char *enc)
  500. {
  501. return PyFile_SetEncodingAndErrors(f, enc, NULL);
  502. }
  503. int
  504. PyFile_SetEncodingAndErrors(PyObject *f, const char *enc, char* errors)
  505. {
  506. PyFileObject *file = (PyFileObject*)f;
  507. PyObject *str, *oerrors;
  508. assert(PyFile_Check(f));
  509. str = PyString_FromString(enc);
  510. if (!str)
  511. return 0;
  512. if (errors) {
  513. oerrors = PyString_FromString(errors);
  514. if (!oerrors) {
  515. Py_DECREF(str);
  516. return 0;
  517. }
  518. } else {
  519. oerrors = Py_None;
  520. Py_INCREF(Py_None);
  521. }
  522. Py_DECREF(file->f_encoding);
  523. file->f_encoding = str;
  524. Py_DECREF(file->f_errors);
  525. file->f_errors = oerrors;
  526. return 1;
  527. }
  528. static PyObject *
  529. err_closed(void)
  530. {
  531. PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
  532. return NULL;
  533. }
  534. static PyObject *
  535. err_mode(char *action)
  536. {
  537. PyErr_Format(PyExc_IOError, "File not open for %s", action);
  538. return NULL;
  539. }
  540. /* Refuse regular file I/O if there's data in the iteration-buffer.
  541. * Mixing them would cause data to arrive out of order, as the read*
  542. * methods don't use the iteration buffer. */
  543. static PyObject *
  544. err_iterbuffered(void)
  545. {
  546. PyErr_SetString(PyExc_ValueError,
  547. "Mixing iteration and read methods would lose data");
  548. return NULL;
  549. }
  550. static void drop_readahead(PyFileObject *);
  551. /* Methods */
  552. static void
  553. file_dealloc(PyFileObject *f)
  554. {
  555. PyObject *ret;
  556. if (f->weakreflist != NULL)
  557. PyObject_ClearWeakRefs((PyObject *) f);
  558. ret = close_the_file(f);
  559. if (!ret) {
  560. PySys_WriteStderr("close failed in file object destructor:\n");
  561. PyErr_Print();
  562. }
  563. else {
  564. Py_DECREF(ret);
  565. }
  566. PyMem_Free(f->f_setbuf);
  567. Py_XDECREF(f->f_name);
  568. Py_XDECREF(f->f_mode);
  569. Py_XDECREF(f->f_encoding);
  570. Py_XDECREF(f->f_errors);
  571. drop_readahead(f);
  572. Py_TYPE(f)->tp_free((PyObject *)f);
  573. }
  574. static PyObject *
  575. file_repr(PyFileObject *f)
  576. {
  577. PyObject *ret = NULL;
  578. PyObject *name = NULL;
  579. if (PyUnicode_Check(f->f_name)) {
  580. #ifdef Py_USING_UNICODE
  581. const char *name_str;
  582. name = PyUnicode_AsUnicodeEscapeString(f->f_name);
  583. name_str = name ? PyString_AsString(name) : "?";
  584. ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
  585. f->f_fp == NULL ? "closed" : "open",
  586. name_str,
  587. PyString_AsString(f->f_mode),
  588. f);
  589. Py_XDECREF(name);
  590. return ret;
  591. #endif
  592. } else {
  593. name = PyObject_Repr(f->f_name);
  594. if (name == NULL)
  595. return NULL;
  596. ret = PyString_FromFormat("<%s file %s, mode '%s' at %p>",
  597. f->f_fp == NULL ? "closed" : "open",
  598. PyString_AsString(name),
  599. PyString_AsString(f->f_mode),
  600. f);
  601. Py_XDECREF(name);
  602. return ret;
  603. }
  604. }
  605. static PyObject *
  606. file_close(PyFileObject *f)
  607. {
  608. PyObject *sts = close_the_file(f);
  609. if (sts) {
  610. PyMem_Free(f->f_setbuf);
  611. f->f_setbuf = NULL;
  612. }
  613. return sts;
  614. }
  615. /* Our very own off_t-like type, 64-bit if possible */
  616. #if !defined(HAVE_LARGEFILE_SUPPORT)
  617. typedef off_t Py_off_t;
  618. #elif SIZEOF_OFF_T >= 8
  619. typedef off_t Py_off_t;
  620. #elif SIZEOF_FPOS_T >= 8
  621. typedef fpos_t Py_off_t;
  622. #else
  623. #error "Large file support, but neither off_t nor fpos_t is large enough."
  624. #endif
  625. /* a portable fseek() function
  626. return 0 on success, non-zero on failure (with errno set) */
  627. static int
  628. _portable_fseek(FILE *fp, Py_off_t offset, int whence)
  629. {
  630. #if !defined(HAVE_LARGEFILE_SUPPORT)
  631. return fseek(fp, offset, whence);
  632. #elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
  633. return fseeko(fp, offset, whence);
  634. #elif defined(HAVE_FSEEK64)
  635. return fseek64(fp, offset, whence);
  636. #elif defined(__BEOS__)
  637. return _fseek(fp, offset, whence);
  638. #elif SIZEOF_FPOS_T >= 8
  639. /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
  640. and fgetpos() to implement fseek()*/
  641. fpos_t pos;
  642. switch (whence) {
  643. case SEEK_END:
  644. #ifdef MS_WINDOWS
  645. fflush(fp);
  646. if (_lseeki64(fileno(fp), 0, 2) == -1)
  647. return -1;
  648. #else
  649. if (fseek(fp, 0, SEEK_END) != 0)
  650. return -1;
  651. #endif
  652. /* fall through */
  653. case SEEK_CUR:
  654. if (fgetpos(fp, &pos) != 0)
  655. return -1;
  656. offset += pos;
  657. break;
  658. /* case SEEK_SET: break; */
  659. }
  660. return fsetpos(fp, &offset);
  661. #else
  662. #error "Large file support, but no way to fseek."
  663. #endif
  664. }
  665. /* a portable ftell() function
  666. Return -1 on failure with errno set appropriately, current file
  667. position on success */
  668. static Py_off_t
  669. _portable_ftell(FILE* fp)
  670. {
  671. #if !defined(HAVE_LARGEFILE_SUPPORT)
  672. return ftell(fp);
  673. #elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
  674. return ftello(fp);
  675. #elif defined(HAVE_FTELL64)
  676. return ftell64(fp);
  677. #elif SIZEOF_FPOS_T >= 8
  678. fpos_t pos;
  679. if (fgetpos(fp, &pos) != 0)
  680. return -1;
  681. return pos;
  682. #else
  683. #error "Large file support, but no way to ftell."
  684. #endif
  685. }
  686. static PyObject *
  687. file_seek(PyFileObject *f, PyObject *args)
  688. {
  689. int whence;
  690. int ret;
  691. Py_off_t offset;
  692. PyObject *offobj, *off_index;
  693. if (f->f_fp == NULL)
  694. return err_closed();
  695. drop_readahead(f);
  696. whence = 0;
  697. if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
  698. return NULL;
  699. off_index = PyNumber_Index(offobj);
  700. if (!off_index) {
  701. if (!PyFloat_Check(offobj))
  702. return NULL;
  703. /* Deprecated in 2.6 */
  704. PyErr_Clear();
  705. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  706. "integer argument expected, got float",
  707. 1) < 0)
  708. return NULL;
  709. off_index = offobj;
  710. Py_INCREF(offobj);
  711. }
  712. #if !defined(HAVE_LARGEFILE_SUPPORT)
  713. offset = PyInt_AsLong(off_index);
  714. #else
  715. offset = PyLong_Check(off_index) ?
  716. PyLong_AsLongLong(off_index) : PyInt_AsLong(off_index);
  717. #endif
  718. Py_DECREF(off_index);
  719. if (PyErr_Occurred())
  720. return NULL;
  721. FILE_BEGIN_ALLOW_THREADS(f)
  722. errno = 0;
  723. ret = _portable_fseek(f->f_fp, offset, whence);
  724. FILE_END_ALLOW_THREADS(f)
  725. if (ret != 0) {
  726. PyErr_SetFromErrno(PyExc_IOError);
  727. clearerr(f->f_fp);
  728. return NULL;
  729. }
  730. f->f_skipnextlf = 0;
  731. Py_INCREF(Py_None);
  732. return Py_None;
  733. }
  734. #ifdef HAVE_FTRUNCATE
  735. static PyObject *
  736. file_truncate(PyFileObject *f, PyObject *args)
  737. {
  738. Py_off_t newsize;
  739. PyObject *newsizeobj = NULL;
  740. Py_off_t initialpos;
  741. int ret;
  742. if (f->f_fp == NULL)
  743. return err_closed();
  744. if (!f->writable)
  745. return err_mode("writing");
  746. if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
  747. return NULL;
  748. /* Get current file position. If the file happens to be open for
  749. * update and the last operation was an input operation, C doesn't
  750. * define what the later fflush() will do, but we promise truncate()
  751. * won't change the current position (and fflush() *does* change it
  752. * then at least on Windows). The easiest thing is to capture
  753. * current pos now and seek back to it at the end.
  754. */
  755. FILE_BEGIN_ALLOW_THREADS(f)
  756. errno = 0;
  757. initialpos = _portable_ftell(f->f_fp);
  758. FILE_END_ALLOW_THREADS(f)
  759. if (initialpos == -1)
  760. goto onioerror;
  761. /* Set newsize to current postion if newsizeobj NULL, else to the
  762. * specified value.
  763. */
  764. if (newsizeobj != NULL) {
  765. #if !defined(HAVE_LARGEFILE_SUPPORT)
  766. newsize = PyInt_AsLong(newsizeobj);
  767. #else
  768. newsize = PyLong_Check(newsizeobj) ?
  769. PyLong_AsLongLong(newsizeobj) :
  770. PyInt_AsLong(newsizeobj);
  771. #endif
  772. if (PyErr_Occurred())
  773. return NULL;
  774. }
  775. else /* default to current position */
  776. newsize = initialpos;
  777. /* Flush the stream. We're mixing stream-level I/O with lower-level
  778. * I/O, and a flush may be necessary to synch both platform views
  779. * of the current file state.
  780. */
  781. FILE_BEGIN_ALLOW_THREADS(f)
  782. errno = 0;
  783. ret = fflush(f->f_fp);
  784. FILE_END_ALLOW_THREADS(f)
  785. if (ret != 0)
  786. goto onioerror;
  787. #ifdef MS_WINDOWS
  788. /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
  789. so don't even try using it. */
  790. {
  791. HANDLE hFile;
  792. /* Have to move current pos to desired endpoint on Windows. */
  793. FILE_BEGIN_ALLOW_THREADS(f)
  794. errno = 0;
  795. ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
  796. FILE_END_ALLOW_THREADS(f)
  797. if (ret)
  798. goto onioerror;
  799. /* Truncate. Note that this may grow the file! */
  800. FILE_BEGIN_ALLOW_THREADS(f)
  801. errno = 0;
  802. hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
  803. ret = hFile == (HANDLE)-1;
  804. if (ret == 0) {
  805. ret = SetEndOfFile(hFile) == 0;
  806. if (ret)
  807. errno = EACCES;
  808. }
  809. FILE_END_ALLOW_THREADS(f)
  810. if (ret)
  811. goto onioerror;
  812. }
  813. #else
  814. FILE_BEGIN_ALLOW_THREADS(f)
  815. errno = 0;
  816. ret = ftruncate(fileno(f->f_fp), newsize);
  817. FILE_END_ALLOW_THREADS(f)
  818. if (ret != 0)
  819. goto onioerror;
  820. #endif /* !MS_WINDOWS */
  821. /* Restore original file position. */
  822. FILE_BEGIN_ALLOW_THREADS(f)
  823. errno = 0;
  824. ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
  825. FILE_END_ALLOW_THREADS(f)
  826. if (ret)
  827. goto onioerror;
  828. Py_INCREF(Py_None);
  829. return Py_None;
  830. onioerror:
  831. PyErr_SetFromErrno(PyExc_IOError);
  832. clearerr(f->f_fp);
  833. return NULL;
  834. }
  835. #endif /* HAVE_FTRUNCATE */
  836. static PyObject *
  837. file_tell(PyFileObject *f)
  838. {
  839. Py_off_t pos;
  840. if (f->f_fp == NULL)
  841. return err_closed();
  842. FILE_BEGIN_ALLOW_THREADS(f)
  843. errno = 0;
  844. pos = _portable_ftell(f->f_fp);
  845. FILE_END_ALLOW_THREADS(f)
  846. if (pos == -1) {
  847. PyErr_SetFromErrno(PyExc_IOError);
  848. clearerr(f->f_fp);
  849. return NULL;
  850. }
  851. if (f->f_skipnextlf) {
  852. int c;
  853. c = GETC(f->f_fp);
  854. if (c == '\n') {
  855. f->f_newlinetypes |= NEWLINE_CRLF;
  856. pos++;
  857. f->f_skipnextlf = 0;
  858. } else if (c != EOF) ungetc(c, f->f_fp);
  859. }
  860. #if !defined(HAVE_LARGEFILE_SUPPORT)
  861. return PyInt_FromLong(pos);
  862. #else
  863. return PyLong_FromLongLong(pos);
  864. #endif
  865. }
  866. static PyObject *
  867. file_fileno(PyFileObject *f)
  868. {
  869. if (f->f_fp == NULL)
  870. return err_closed();
  871. return PyInt_FromLong((long) fileno(f->f_fp));
  872. }
  873. static PyObject *
  874. file_flush(PyFileObject *f)
  875. {
  876. int res;
  877. if (f->f_fp == NULL)
  878. return err_closed();
  879. FILE_BEGIN_ALLOW_THREADS(f)
  880. errno = 0;
  881. res = fflush(f->f_fp);
  882. FILE_END_ALLOW_THREADS(f)
  883. if (res != 0) {
  884. PyErr_SetFromErrno(PyExc_IOError);
  885. clearerr(f->f_fp);
  886. return NULL;
  887. }
  888. Py_INCREF(Py_None);
  889. return Py_None;
  890. }
  891. static PyObject *
  892. file_isatty(PyFileObject *f)
  893. {
  894. long res;
  895. if (f->f_fp == NULL)
  896. return err_closed();
  897. FILE_BEGIN_ALLOW_THREADS(f)
  898. res = isatty((int)fileno(f->f_fp));
  899. FILE_END_ALLOW_THREADS(f)
  900. return PyBool_FromLong(res);
  901. }
  902. #if BUFSIZ < 8192
  903. #define SMALLCHUNK 8192
  904. #else
  905. #define SMALLCHUNK BUFSIZ
  906. #endif
  907. static size_t
  908. new_buffersize(PyFileObject *f, size_t currentsize)
  909. {
  910. #ifdef HAVE_FSTAT
  911. off_t pos, end;
  912. struct stat st;
  913. if (fstat(fileno(f->f_fp), &st) == 0) {
  914. end = st.st_size;
  915. /* The following is not a bug: we really need to call lseek()
  916. *and* ftell(). The reason is that some stdio libraries
  917. mistakenly flush their buffer when ftell() is called and
  918. the lseek() call it makes fails, thereby throwing away
  919. data that cannot be recovered in any way. To avoid this,
  920. we first test lseek(), and only call ftell() if lseek()
  921. works. We can't use the lseek() value either, because we
  922. need to take the amount of buffered data into account.
  923. (Yet another reason why stdio stinks. :-) */
  924. pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
  925. if (pos >= 0) {
  926. pos = ftell(f->f_fp);
  927. }
  928. if (pos < 0)
  929. clearerr(f->f_fp);
  930. if (end > pos && pos >= 0)
  931. return currentsize + end - pos + 1;
  932. /* Add 1 so if the file were to grow we'd notice. */
  933. }
  934. #endif
  935. /* Expand the buffer by an amount proportional to the current size,
  936. giving us amortized linear-time behavior. Use a less-than-double
  937. growth factor to avoid excessive allocation. */
  938. return currentsize + (currentsize >> 3) + 6;
  939. }
  940. #if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
  941. #define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
  942. #else
  943. #ifdef EWOULDBLOCK
  944. #define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
  945. #else
  946. #ifdef EAGAIN
  947. #define BLOCKED_ERRNO(x) ((x) == EAGAIN)
  948. #else
  949. #define BLOCKED_ERRNO(x) 0
  950. #endif
  951. #endif
  952. #endif
  953. static PyObject *
  954. file_read(PyFileObject *f, PyObject *args)
  955. {
  956. long bytesrequested = -1;
  957. size_t bytesread, buffersize, chunksize;
  958. PyObject *v;
  959. if (f->f_fp == NULL)
  960. return err_closed();
  961. if (!f->readable)
  962. return err_mode("reading");
  963. /* refuse to mix with f.next() */
  964. if (f->f_buf != NULL &&
  965. (f->f_bufend - f->f_bufptr) > 0 &&
  966. f->f_buf[0] != '\0')
  967. return err_iterbuffered();
  968. if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
  969. return NULL;
  970. if (bytesrequested < 0)
  971. buffersize = new_buffersize(f, (size_t)0);
  972. else
  973. buffersize = bytesrequested;
  974. if (buffersize > PY_SSIZE_T_MAX) {
  975. PyErr_SetString(PyExc_OverflowError,
  976. "requested number of bytes is more than a Python string can hold");
  977. return NULL;
  978. }
  979. v = PyString_FromStringAndSize((char *)NULL, buffersize);
  980. if (v == NULL)
  981. return NULL;
  982. bytesread = 0;
  983. for (;;) {
  984. int interrupted;
  985. FILE_BEGIN_ALLOW_THREADS(f)
  986. errno = 0;
  987. chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
  988. buffersize - bytesread, f->f_fp, (PyObject *)f);
  989. interrupted = ferror(f->f_fp) && errno == EINTR;
  990. FILE_END_ALLOW_THREADS(f)
  991. if (interrupted) {
  992. clearerr(f->f_fp);
  993. if (PyErr_CheckSignals()) {
  994. Py_DECREF(v);
  995. return NULL;
  996. }
  997. }
  998. if (chunksize == 0) {
  999. if (interrupted)
  1000. continue;
  1001. if (!ferror(f->f_fp))
  1002. break;
  1003. clearerr(f->f_fp);
  1004. /* When in non-blocking mode, data shouldn't
  1005. * be discarded if a blocking signal was
  1006. * received. That will also happen if
  1007. * chunksize != 0, but bytesread < buffersize. */
  1008. if (bytesread > 0 && BLOCKED_ERRNO(errno))
  1009. break;
  1010. PyErr_SetFromErrno(PyExc_IOError);
  1011. Py_DECREF(v);
  1012. return NULL;
  1013. }
  1014. bytesread += chunksize;
  1015. if (bytesread < buffersize && !interrupted) {
  1016. clearerr(f->f_fp);
  1017. break;
  1018. }
  1019. if (bytesrequested < 0) {
  1020. buffersize = new_buffersize(f, buffersize);
  1021. if (_PyString_Resize(&v, buffersize) < 0)
  1022. return NULL;
  1023. } else {
  1024. /* Got what was requested. */
  1025. break;
  1026. }
  1027. }
  1028. if (bytesread != buffersize && _PyString_Resize(&v, bytesread))
  1029. return NULL;
  1030. return v;
  1031. }
  1032. static PyObject *
  1033. file_readinto(PyFileObject *f, PyObject *args)
  1034. {
  1035. char *ptr;
  1036. Py_ssize_t ntodo;
  1037. Py_ssize_t ndone, nnow;
  1038. Py_buffer pbuf;
  1039. if (f->f_fp == NULL)
  1040. return err_closed();
  1041. if (!f->readable)
  1042. return err_mode("reading");
  1043. /* refuse to mix with f.next() */
  1044. if (f->f_buf != NULL &&
  1045. (f->f_bufend - f->f_bufptr) > 0 &&
  1046. f->f_buf[0] != '\0')
  1047. return err_iterbuffered();
  1048. if (!PyArg_ParseTuple(args, "w*", &pbuf))
  1049. return NULL;
  1050. ptr = pbuf.buf;
  1051. ntodo = pbuf.len;
  1052. ndone = 0;
  1053. while (ntodo > 0) {
  1054. int interrupted;
  1055. FILE_BEGIN_ALLOW_THREADS(f)
  1056. errno = 0;
  1057. nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
  1058. (PyObject *)f);
  1059. interrupted = ferror(f->f_fp) && errno == EINTR;
  1060. FILE_END_ALLOW_THREADS(f)
  1061. if (interrupted) {
  1062. clearerr(f->f_fp);
  1063. if (PyErr_CheckSignals()) {
  1064. PyBuffer_Release(&pbuf);
  1065. return NULL;
  1066. }
  1067. }
  1068. if (nnow == 0) {
  1069. if (interrupted)
  1070. continue;
  1071. if (!ferror(f->f_fp))
  1072. break;
  1073. PyErr_SetFromErrno(PyExc_IOError);
  1074. clearerr(f->f_fp);
  1075. PyBuffer_Release(&pbuf);
  1076. return NULL;
  1077. }
  1078. ndone += nnow;
  1079. ntodo -= nnow;
  1080. }
  1081. PyBuffer_Release(&pbuf);
  1082. return PyInt_FromSsize_t(ndone);
  1083. }
  1084. /**************************************************************************
  1085. Routine to get next line using platform fgets().
  1086. Under MSVC 6:
  1087. + MS threadsafe getc is very slow (multiple layers of function calls before+
  1088. after each character, to lock+unlock the stream).
  1089. + The stream-locking functions are MS-internal -- can't access them from user
  1090. code.
  1091. + There's nothing Tim could find in the MS C or platform SDK libraries that
  1092. can worm around this.
  1093. + MS fgets locks/unlocks only once per line; it's the only hook we have.
  1094. So we use fgets for speed(!), despite that it's painful.
  1095. MS realloc is also slow.
  1096. Reports from other platforms on this method vs getc_unlocked (which MS doesn't
  1097. have):
  1098. Linux a wash
  1099. Solaris a wash
  1100. Tru64 Unix getline_via_fgets significantly faster
  1101. CAUTION: The C std isn't clear about this: in those cases where fgets
  1102. writes something into the buffer, can it write into any position beyond the
  1103. required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
  1104. known on which it does; and it would be a strange way to code fgets. Still,
  1105. getline_via_fgets may not work correctly if it does. The std test
  1106. test_bufio.py should fail if platform fgets() routinely writes beyond the
  1107. trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
  1108. **************************************************************************/
  1109. /* Use this routine if told to, or by default on non-get_unlocked()
  1110. * platforms unless told not to. Yikes! Let's spell that out:
  1111. * On a platform with getc_unlocked():
  1112. * By default, use getc_unlocked().
  1113. * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
  1114. * On a platform without getc_unlocked():
  1115. * By default, use fgets().
  1116. * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
  1117. */
  1118. #if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
  1119. #define USE_FGETS_IN_GETLINE
  1120. #endif
  1121. #if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
  1122. #undef USE_FGETS_IN_GETLINE
  1123. #endif
  1124. #ifdef USE_FGETS_IN_GETLINE
  1125. static PyObject*
  1126. getline_via_fgets(PyFileObject *f, FILE *fp)
  1127. {
  1128. /* INITBUFSIZE is the maximum line length that lets us get away with the fast
  1129. * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
  1130. * to fill this much of the buffer with a known value in order to figure out
  1131. * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
  1132. * than "most" lines, we waste time filling unused buffer slots. 100 is
  1133. * surely adequate for most peoples' email archives, chewing over source code,
  1134. * etc -- "regular old text files".
  1135. * MAXBUFSIZE is the maximum line length that lets us get away with the less
  1136. * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
  1137. * cautions about boosting that. 300 was chosen because the worst real-life
  1138. * text-crunching job reported on Python-Dev was a mail-log crawler where over
  1139. * half the lines were 254 chars.
  1140. */
  1141. #define INITBUFSIZE 100
  1142. #define MAXBUFSIZE 300
  1143. char* p; /* temp */
  1144. char buf[MAXBUFSIZE];
  1145. PyObject* v; /* the string object result */
  1146. char* pvfree; /* address of next free slot */
  1147. char* pvend; /* address one beyond last free slot */
  1148. size_t nfree; /* # of free buffer slots; pvend-pvfree */
  1149. size_t total_v_size; /* total # of slots in buffer */
  1150. size_t increment; /* amount to increment the buffer */
  1151. size_t prev_v_size;
  1152. /* Optimize for normal case: avoid _PyString_Resize if at all
  1153. * possible via first reading into stack buffer "buf".
  1154. */
  1155. total_v_size = INITBUFSIZE; /* start small and pray */
  1156. pvfree = buf;
  1157. for (;;) {
  1158. FILE_BEGIN_ALLOW_THREADS(f)
  1159. pvend = buf + total_v_size;
  1160. nfree = pvend - pvfree;
  1161. memset(pvfree, '\n', nfree);
  1162. assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
  1163. p = fgets(pvfree, (int)nfree, fp);
  1164. FILE_END_ALLOW_THREADS(f)
  1165. if (p == NULL) {
  1166. clearerr(fp);
  1167. if (PyErr_CheckSignals())
  1168. return NULL;
  1169. v = PyString_FromStringAndSize(buf, pvfree - buf);
  1170. return v;
  1171. }
  1172. /* fgets read *something* */
  1173. p = memchr(pvfree, '\n', nfree);
  1174. if (p != NULL) {
  1175. /* Did the \n come from fgets or from us?
  1176. * Since fgets stops at the first \n, and then writes
  1177. * \0, if it's from fgets a \0 must be next. But if
  1178. * that's so, it could not have come from us, since
  1179. * the \n's we filled the buffer with have only more
  1180. * \n's to the right.
  1181. */
  1182. if (p+1 < pvend && *(p+1) == '\0') {
  1183. /* It's from fgets: we win! In particular,
  1184. * we haven't done any mallocs yet, and can
  1185. * build the final result on the first try.
  1186. */
  1187. ++p; /* include \n from fgets */
  1188. }
  1189. else {
  1190. /* Must be from us: fgets didn't fill the
  1191. * buffer and didn't find a newline, so it
  1192. * must be the last and newline-free line of
  1193. * the file.
  1194. */
  1195. assert(p > pvfree && *(p-1) == '\0');
  1196. --p; /* don't include \0 from fgets */
  1197. }
  1198. v = PyString_FromStringAndSize(buf, p - buf);
  1199. return v;
  1200. }
  1201. /* yuck: fgets overwrote all the newlines, i.e. the entire
  1202. * buffer. So this line isn't over yet, or maybe it is but
  1203. * we're exactly at EOF. If we haven't already, try using the
  1204. * rest of the stack buffer.
  1205. */
  1206. assert(*(pvend-1) == '\0');
  1207. if (pvfree == buf) {
  1208. pvfree = pvend - 1; /* overwrite trailing null */
  1209. total_v_size = MAXBUFSIZE;
  1210. }
  1211. else
  1212. break;
  1213. }
  1214. /* The stack buffer isn't big enough; malloc a string object and read
  1215. * into its buffer.
  1216. */
  1217. total_v_size = MAXBUFSIZE << 1;
  1218. v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
  1219. if (v == NULL)
  1220. return v;
  1221. /* copy over everything except the last null byte */
  1222. memcpy(BUF(v), buf, MAXBUFSIZE-1);
  1223. pvfree = BUF(v) + MAXBUFSIZE - 1;
  1224. /* Keep reading stuff into v; if it ever ends successfully, break
  1225. * after setting p one beyond the end of the line. The code here is
  1226. * very much like the code above, except reads into v's buffer; see
  1227. * the code above for detailed comments about the logic.
  1228. */
  1229. for (;;) {
  1230. FILE_BEGIN_ALLOW_THREADS(f)
  1231. pvend = BUF(v) + total_v_size;
  1232. nfree = pvend - pvfree;
  1233. memset(pvfree, '\n', nfree);
  1234. assert(nfree < INT_MAX);
  1235. p = fgets(pvfree, (int)nfree, fp);
  1236. FILE_END_ALLOW_THREADS(f)
  1237. if (p == NULL) {
  1238. clearerr(fp);
  1239. if (PyErr_CheckSignals()) {
  1240. Py_DECREF(v);
  1241. return NULL;
  1242. }
  1243. p = pvfree;
  1244. break;
  1245. }
  1246. p = memchr(pvfree, '\n', nfree);
  1247. if (p != NULL) {
  1248. if (p+1 < pvend && *(p+1) == '\0') {
  1249. /* \n came from fgets */
  1250. ++p;
  1251. break;
  1252. }
  1253. /* \n came from us; last line of file, no newline */
  1254. assert(p > pvfree && *(p-1) == '\0');
  1255. --p;
  1256. break;
  1257. }
  1258. /* expand buffer and try again */
  1259. assert(*(pvend-1) == '\0');
  1260. increment = total_v_size >> 2; /* mild exponential growth */
  1261. prev_v_size = total_v_size;
  1262. total_v_size += increment;
  1263. /* check for overflow */
  1264. if (total_v_size <= prev_v_size ||
  1265. total_v_size > PY_SSIZE_T_MAX) {
  1266. PyErr_SetString(PyExc_OverflowError,
  1267. "line is longer than a Python string can hold");
  1268. Py_DECREF(v);
  1269. return NULL;
  1270. }
  1271. if (_PyString_Resize(&v, (int)total_v_size) < 0)
  1272. return NULL;
  1273. /* overwrite the trailing null byte */
  1274. pvfree = BUF(v) + (prev_v_size - 1);
  1275. }
  1276. if (BUF(v) + total_v_size != p && _PyString_Resize(&v, p - BUF(v)))
  1277. return NULL;
  1278. return v;
  1279. #undef INITBUFSIZE
  1280. #undef MAXBUFSIZE
  1281. }
  1282. #endif /* ifdef USE_FGETS_IN_GETLINE */
  1283. /* Internal routine to get a line.
  1284. Size argument interpretation:
  1285. > 0: max length;
  1286. <= 0: read arbitrary line
  1287. */
  1288. static PyObject *
  1289. get_line(PyFileObject *f, int n)
  1290. {
  1291. FILE *fp = f->f_fp;
  1292. int c;
  1293. char *buf, *end;
  1294. size_t total_v_size; /* total # of slots in buffer */
  1295. size_t used_v_size; /* # used slots in buffer */
  1296. size_t increment; /* amount to increment the buffer */
  1297. PyObject *v;
  1298. int newlinetypes = f->f_newlinetypes;
  1299. int skipnextlf = f->f_skipnextlf;
  1300. int univ_newline = f->f_univ_newline;
  1301. #if defined(USE_FGETS_IN_GETLINE)
  1302. if (n <= 0 && !univ_newline )
  1303. return getline_via_fgets(f, fp);
  1304. #endif
  1305. total_v_size = n > 0 ? n : 100;
  1306. v = PyString_FromStringAndSize((char *)NULL, total_v_size);
  1307. if (v == NULL)
  1308. return NULL;
  1309. buf = BUF(v);
  1310. end = buf + total_v_size;
  1311. for (;;) {
  1312. FILE_BEGIN_ALLOW_THREADS(f)
  1313. FLOCKFILE(fp);
  1314. if (univ_newline) {
  1315. c = 'x'; /* Shut up gcc warning */
  1316. while ( buf != end && (c = GETC(fp)) != EOF ) {
  1317. if (skipnextlf ) {
  1318. skipnextlf = 0;
  1319. if (c == '\n') {
  1320. /* Seeing a \n here with
  1321. * skipnextlf true means we
  1322. * saw a \r before.
  1323. */
  1324. newlinetypes |= NEWLINE_CRLF;
  1325. c = GETC(fp);
  1326. if (c == EOF) break;
  1327. } else {
  1328. newlinetypes |= NEWLINE_CR;
  1329. }
  1330. }
  1331. if (c == '\r') {
  1332. skipnextlf = 1;
  1333. c = '\n';
  1334. } else if ( c == '\n')
  1335. newlinetypes |= NEWLINE_LF;
  1336. *buf++ = c;
  1337. if (c == '\n') break;
  1338. }
  1339. if (c == EOF) {
  1340. if (ferror(fp) && errno == EINTR) {
  1341. FUNLOCKFILE(fp);
  1342. FILE_ABORT_ALLOW_THREADS(f)
  1343. f->f_newlinetypes = newlinetypes;
  1344. f->f_skipnextlf = skipnextlf;
  1345. if (PyErr_CheckSignals()) {
  1346. Py_DECREF(v);
  1347. return NULL;
  1348. }
  1349. /* We executed Python signal handlers and got no exception.
  1350. * Now back to reading the line where we left off. */
  1351. clearerr(fp);
  1352. continue;
  1353. }
  1354. if (skipnextlf)
  1355. newlinetypes |= NEWLINE_CR;
  1356. }
  1357. } else /* If not universal newlines use the normal loop */
  1358. while ((c = GETC(fp)) != EOF &&
  1359. (*buf++ = c) != '\n' &&
  1360. buf != end)
  1361. ;
  1362. FUNLOCKFILE(fp);
  1363. FILE_END_ALLOW_THREADS(f)
  1364. f->f_newlinetypes = newlinetypes;
  1365. f->f_skipnextlf = skipnextlf;
  1366. if (c == '\n')
  1367. break;
  1368. if (c == EOF) {
  1369. if (ferror(fp)) {
  1370. if (errno == EINTR) {
  1371. if (PyErr_CheckSignals()) {
  1372. Py_DECREF(v);
  1373. return NULL;
  1374. }
  1375. /* We executed Python signal handlers and got no exception.
  1376. * Now back to reading the line where we left off. */
  1377. clearerr(fp);
  1378. continue;
  1379. }
  1380. PyErr_SetFromErrno(PyExc_IOError);
  1381. clearerr(fp);
  1382. Py_DECREF(v);
  1383. return NULL;
  1384. }
  1385. clearerr(fp);
  1386. if (PyErr_CheckSignals()) {
  1387. Py_DECREF(v);
  1388. return NULL;
  1389. }
  1390. break;
  1391. }
  1392. /* Must be because buf == end */
  1393. if (n > 0)
  1394. break;
  1395. used_v_size = total_v_size;
  1396. increment = total_v_size >> 2; /* mild exponential growth */
  1397. total_v_size += increment;
  1398. if (total_v_size > PY_SSIZE_T_MAX) {
  1399. PyErr_SetString(PyExc_OverflowError,
  1400. "line is longer than a Python string can hold");
  1401. Py_DECREF(v);
  1402. return NULL;
  1403. }
  1404. if (_PyString_Resize(&v, total_v_size) < 0)
  1405. return NULL;
  1406. buf = BUF(v) + used_v_size;
  1407. end = BUF(v) + total_v_size;
  1408. }
  1409. used_v_size = buf - BUF(v);
  1410. if (used_v_size != total_v_size && _PyString_Resize(&v, used_v_size))
  1411. return NULL;
  1412. return v;
  1413. }
  1414. /* External C interface */
  1415. PyObject *
  1416. PyFile_GetLine(PyObject *f, int n)
  1417. {
  1418. PyObject *result;
  1419. if (f == NULL) {
  1420. PyErr_BadInternalCall();
  1421. return NULL;
  1422. }
  1423. if (PyFile_Check(f)) {
  1424. PyFileObject *fo = (PyFileObject *)f;
  1425. if (fo->f_fp == NULL)
  1426. return err_closed();
  1427. if (!fo->readable)
  1428. return err_mode("reading");
  1429. /* refuse to mix with f.next() */
  1430. if (fo->f_buf != NULL &&
  1431. (fo->f_bufend - fo->f_bufptr) > 0 &&
  1432. fo->f_buf[0] != '\0')
  1433. return err_iterbuffered();
  1434. result = get_line(fo, n);
  1435. }
  1436. else {
  1437. PyObject *reader;
  1438. PyObject *args;
  1439. reader = PyObject_GetAttrString(f, "readline");
  1440. if (reader == NULL)
  1441. return NULL;
  1442. if (n <= 0)
  1443. args = PyTuple_New(0);
  1444. else
  1445. args = Py_BuildValue("(i)", n);
  1446. if (args == NULL) {
  1447. Py_DECREF(reader);
  1448. return NULL;
  1449. }
  1450. result = PyEval_CallObject(reader, args);
  1451. Py_DECREF(reader);
  1452. Py_DECREF(args);
  1453. if (result != NULL && !PyString_Check(result) &&
  1454. !PyUnicode_Check(result)) {
  1455. Py_DECREF(result);
  1456. result = NULL;
  1457. PyErr_SetString(PyExc_TypeError,
  1458. "object.readline() returned non-string");
  1459. }
  1460. }
  1461. if (n < 0 && result != NULL && PyString_Check(result)) {
  1462. char *s = PyString_AS_STRING(result);
  1463. Py_ssize_t len = PyString_GET_SIZE(result);
  1464. if (len == 0) {
  1465. Py_DECREF(result);
  1466. result = NULL;
  1467. PyErr_SetString(PyExc_EOFError,
  1468. "EOF when reading a line");
  1469. }
  1470. else if (s[len-1] == '\n') {
  1471. if (result->ob_refcnt == 1) {
  1472. if (_PyString_Resize(&result, len-1))
  1473. return NULL;
  1474. }
  1475. else {
  1476. PyObject *v;
  1477. v = PyString_FromStringAndSize(s, len-1);
  1478. Py_DECREF(result);
  1479. result = v;
  1480. }
  1481. }
  1482. }
  1483. #ifdef Py_USING_UNICODE
  1484. if (n < 0 && result != NULL && PyUnicode_Check(result)) {
  1485. Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
  1486. Py_ssize_t len = PyUnicode_GET_SIZE(result);
  1487. if (len == 0) {
  1488. Py_DECREF(result);
  1489. result = NULL;
  1490. PyErr_SetString(PyExc_EOFError,
  1491. "EOF when reading a line");
  1492. }
  1493. else if (s[len-1] == '\n') {
  1494. if (result->ob_refcnt == 1)
  1495. PyUnicode_Resize(&result, len-1);
  1496. else {
  1497. PyObject *v;
  1498. v = PyUnicode_FromUnicode(s, len-1);
  1499. Py_DECREF(result);
  1500. result = v;
  1501. }
  1502. }
  1503. }
  1504. #endif
  1505. return result;
  1506. }
  1507. /* Python method */
  1508. static PyObject *
  1509. file_readline(PyFileObject *f, PyObject *args)
  1510. {
  1511. int n = -1;
  1512. if (f->f_fp == NULL)
  1513. return err_closed();
  1514. if (!f->readable)
  1515. return err_mode("reading");
  1516. /* refuse to mix with f.next() */
  1517. if (f->f_buf != NULL &&
  1518. (f->f_bufend - f->f_bufptr) > 0 &&
  1519. f->f_buf[0] != '\0')
  1520. return err_iterbuffered();
  1521. if (!PyArg_ParseTuple(args, "|i:readline", &n))
  1522. return NULL;
  1523. if (n == 0)
  1524. return PyString_FromString("");
  1525. if (n < 0)
  1526. n = 0;
  1527. return get_line(f, n);
  1528. }
  1529. static PyObject *
  1530. file_readlines(PyFileObject *f, PyObject *args)
  1531. {
  1532. long sizehint = 0;
  1533. PyObject *list = NULL;
  1534. PyObject *line;
  1535. char small_buffer[SMALLCHUNK];
  1536. char *buffer = small_buffer;
  1537. size_t buffersize = SMALLCHUNK;
  1538. PyObject *big_buffer = NULL;
  1539. size_t nfilled = 0;
  1540. size_t nread;
  1541. size_t totalread = 0;
  1542. char *p, *q, *end;
  1543. int err;
  1544. int shortread = 0; /* bool, did the previous read come up short? */
  1545. if (f->f_fp == NULL)
  1546. return err_closed();
  1547. if (!f->readable)
  1548. return err_mode("reading");
  1549. /* refuse to mix with f.next() */
  1550. if (f->f_buf != NULL &&
  1551. (f->f_bufend - f->f_bufptr) > 0 &&
  1552. f->f_buf[0] != '\0')
  1553. return err_iterbuffered();
  1554. if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
  1555. return NULL;
  1556. if ((list = PyList_New(0)) == NULL)
  1557. return NULL;
  1558. for (;;) {
  1559. if (shortread)
  1560. nread = 0;
  1561. else {
  1562. FILE_BEGIN_ALLOW_THREADS(f)
  1563. errno = 0;
  1564. nread = Py_UniversalNewlineFread(buffer+nfilled,
  1565. buffersize-nfilled, f->f_fp, (PyObject *)f);
  1566. FILE_END_ALLOW_THREADS(f)
  1567. shortread = (nread < buffersize-nfilled);
  1568. }
  1569. if (nread == 0) {
  1570. sizehint = 0;
  1571. if (!ferror(f->f_fp))
  1572. break;
  1573. if (errno == EINTR) {
  1574. if (PyErr_CheckSignals()) {
  1575. goto error;
  1576. }
  1577. clearerr(f->f_fp);
  1578. shortread = 0;
  1579. continue;
  1580. }
  1581. PyErr_SetFromErrno(PyExc_IOError);
  1582. clearerr(f->f_fp);
  1583. goto error;
  1584. }
  1585. totalread += nread;
  1586. p = (char *)memchr(buffer+nfilled, '\n', nread);
  1587. if (p == NULL) {
  1588. /* Need a larger buffer to fit this line */
  1589. nfilled += nread;
  1590. buffersize *= 2;
  1591. if (buffersize > PY_SSIZE_T_MAX) {
  1592. PyErr_SetString(PyExc_OverflowError,
  1593. "line is longer than a Python string can hold");
  1594. goto error;
  1595. }
  1596. if (big_buffer == NULL) {
  1597. /* Create the big buffer */
  1598. big_buffer = PyString_FromStringAndSize(
  1599. NULL, buffersize);
  1600. if (big_buffer == NULL)
  1601. goto error;
  1602. buffer = PyString_AS_STRING(big_buffer);
  1603. memcpy(buffer, small_buffer, nfilled);
  1604. }
  1605. else {
  1606. /* Grow the big buffer */
  1607. if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
  1608. goto error;
  1609. buffer = PyString_AS_STRING(big_buffer);
  1610. }
  1611. continue;
  1612. }
  1613. end = buffer+nfilled+nread;
  1614. q = buffer;
  1615. do {
  1616. /* Process complete lines */
  1617. p++;
  1618. line = PyString_FromStringAndSize(q, p-q);
  1619. if (line == NULL)
  1620. goto error;
  1621. err = PyList_Append(list, line);
  1622. Py_DECREF(line);
  1623. if (err != 0)
  1624. goto error;
  1625. q = p;
  1626. p = (char *)memchr(q, '\n', end-q);
  1627. } while (p != NULL);
  1628. /* Move the remaining incomplete line to the start */
  1629. nfilled = end-q;
  1630. memmove(buffer, q, nfilled);
  1631. if (sizehint > 0)
  1632. if (totalread >= (size_t)sizehint)
  1633. break;
  1634. }
  1635. if (nfilled != 0) {
  1636. /* Partial last line */
  1637. line = PyString_FromStringAndSize(buffer, nfilled);
  1638. if (line == NULL)
  1639. goto error;
  1640. if (sizehint > 0) {
  1641. /* Need to complete the last line */
  1642. PyObject *rest = get_line(f, 0);
  1643. if (rest == NULL) {
  1644. Py_DECREF(line);
  1645. goto error;
  1646. }
  1647. PyString_Concat(&line, rest);
  1648. Py_DECREF(rest);
  1649. if (line == NULL)
  1650. goto error;
  1651. }
  1652. err = PyList_Append(list, line);
  1653. Py_DECREF(line);
  1654. if (err != 0)
  1655. goto error;
  1656. }
  1657. cleanup:
  1658. Py_XDECREF(big_buffer);
  1659. return list;
  1660. error:
  1661. Py_CLEAR(list);
  1662. goto cleanup;
  1663. }
  1664. static PyObject *
  1665. file_write(PyFileObject *f, PyObject *args)
  1666. {
  1667. Py_buffer pbuf;
  1668. const char *s;
  1669. Py_ssize_t n, n2;
  1670. PyObject *encoded = NULL;
  1671. if (f->f_fp == NULL)
  1672. return err_closed();
  1673. if (!f->writable)
  1674. return err_mode("writing");
  1675. if (f->f_binary) {
  1676. if (!PyArg_ParseTuple(args, "s*", &pbuf))
  1677. return NULL;
  1678. s = pbuf.buf;
  1679. n = pbuf.len;
  1680. }
  1681. else {
  1682. const char *encoding, *errors;
  1683. PyObject *text;
  1684. if (!PyArg_ParseTuple(args, "O", &text))
  1685. return NULL;
  1686. if (PyString_Check(text)) {
  1687. s = PyString_AS_STRING(text);
  1688. n = PyString_GET_SIZE(text);
  1689. } else if (PyUnicode_Check(text)) {
  1690. if (f->f_encoding != Py_None)
  1691. encoding = PyString_AS_STRING(f->f_encoding);
  1692. else
  1693. encoding = PyUnicode_GetDefaultEncoding();
  1694. if (f->f_errors != Py_None)
  1695. errors = PyString_AS_STRING(f->f_errors);
  1696. else
  1697. errors = "strict";
  1698. encoded = PyUnicode_AsEncodedString(text, encoding, errors);
  1699. if (encoded == NULL)
  1700. return NULL;
  1701. s = PyString_AS_STRING(encoded);
  1702. n = PyString_GET_SIZE(encoded);
  1703. } else {
  1704. if (PyObject_AsCharBuffer(text, &s, &n))
  1705. return NULL;
  1706. }
  1707. }
  1708. f->f_softspace = 0;
  1709. FILE_BEGIN_ALLOW_THREADS(f)
  1710. errno = 0;
  1711. n2 = fwrite(s, 1, n, f->f_fp);
  1712. FILE_END_ALLOW_THREADS(f)
  1713. Py_XDECREF(encoded);
  1714. if (f->f_binary)
  1715. PyBuffer_Release(&pbuf);
  1716. if (n2 != n) {
  1717. PyErr_SetFromErrno(PyExc_IOError);
  1718. clearerr(f->f_fp);
  1719. return NULL;
  1720. }
  1721. Py_INCREF(Py_None);
  1722. return Py_None;
  1723. }
  1724. static PyObject *
  1725. file_writelines(PyFileObject *f, PyObject *seq)
  1726. {
  1727. #define CHUNKSIZE 1000
  1728. PyObject *list, *line;
  1729. PyObject *it; /* iter(seq) */
  1730. PyObject *result;
  1731. int index, islist;
  1732. Py_ssize_t i, j, nwritten, len;
  1733. assert(seq != NULL);
  1734. if (f->f_fp == NULL)
  1735. return err_closed();
  1736. if (!f->writable)
  1737. return err_mode("writing");
  1738. result = NULL;
  1739. list = NULL;
  1740. islist = PyList_Check(seq);
  1741. if (islist)
  1742. it = NULL;
  1743. else {
  1744. it = PyObject_GetIter(seq);
  1745. if (it == NULL) {
  1746. PyErr_SetString(PyExc_TypeError,
  1747. "writelines() requires an iterable argument");
  1748. return NULL;
  1749. }
  1750. /* From here on, fail by going to error, to reclaim "it". */
  1751. list = PyList_New(CHUNKSIZE);
  1752. if (list == NULL)
  1753. goto error;
  1754. }
  1755. /* Strategy: slurp CHUNKSIZE lines into a private list,
  1756. checking that they are all strings, then write that list
  1757. without holding the interpreter lock, then come back for more. */
  1758. for (index = 0; ; index += CHUNKSIZE) {
  1759. if (islist) {
  1760. Py_XDECREF(list);
  1761. list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
  1762. if (list == NULL)
  1763. goto error;
  1764. j = PyList_GET_SIZE(list);
  1765. }
  1766. else {
  1767. for (j = 0; j < CHUNKSIZE; j++) {
  1768. line = PyIter_Next(it);
  1769. if (line == NULL) {
  1770. if (PyErr_Occurred())
  1771. goto error;
  1772. break;
  1773. }
  1774. PyList_SetItem(list, j, line);
  1775. }
  1776. /* The iterator might have closed the file on us. */
  1777. if (f->f_fp == NULL) {
  1778. err_closed();
  1779. goto error;
  1780. }
  1781. }
  1782. if (j == 0)
  1783. break;
  1784. /* Check that all entries are indeed strings. If not,
  1785. apply the same rules as for file.write() and
  1786. convert the results to strings. This is slow, but
  1787. seems to be the only way since all conversion APIs
  1788. could potentially execute Python code. */
  1789. for (i = 0; i < j; i++) {
  1790. PyObject *v = PyList_GET_ITEM(list, i);
  1791. if (!PyString_Check(v)) {
  1792. const char *buffer;
  1793. if (((f->f_binary &&
  1794. PyObject_AsReadBuffer(v,
  1795. (const void**)&buffer,
  1796. &len)) ||
  1797. PyObject_AsCharBuffer(v,
  1798. &buffer,
  1799. &len))) {
  1800. PyErr_SetString(PyExc_TypeError,
  1801. "writelines() argument must be a sequence of strings");
  1802. goto error;
  1803. }
  1804. line = PyString_FromStringAndSize(buffer,
  1805. len);
  1806. if (line == NULL)
  1807. goto error;
  1808. Py_DECREF(v);
  1809. PyList_SET_ITEM(list, i, line);
  1810. }
  1811. }
  1812. /* Since we are releasing the global lock, the
  1813. following code may *not* execute Python code. */
  1814. f->f_softspace = 0;
  1815. FILE_BEGIN_ALLOW_THREADS(f)
  1816. errno = 0;
  1817. for (i = 0; i < j; i++) {
  1818. line = PyList_GET_ITEM(list, i);
  1819. len = PyString_GET_SIZE(line);
  1820. nwritten = fwrite(PyString_AS_STRING(line),
  1821. 1, len, f->f_fp);
  1822. if (nwritten != len) {
  1823. FILE_ABORT_ALLOW_THREADS(f)
  1824. PyErr_SetFromErrno(PyExc_IOError);
  1825. clearerr(f->f_fp);
  1826. goto error;
  1827. }
  1828. }
  1829. FILE_END_ALLOW_THREADS(f)
  1830. if (j < CHUNKSIZE)
  1831. break;
  1832. }
  1833. Py_INCREF(Py_None);
  1834. result = Py_None;
  1835. error:
  1836. Py_XDECREF(list);
  1837. Py_XDECREF(it);
  1838. return result;
  1839. #undef CHUNKSIZE
  1840. }
  1841. static PyObject *
  1842. file_self(PyFileObject *f)
  1843. {
  1844. if (f->f_fp == NULL)
  1845. return err_closed();
  1846. Py_INCREF(f);
  1847. return (PyObject *)f;
  1848. }
  1849. static PyObject *
  1850. file_xreadlines(PyFileObject *f)
  1851. {
  1852. if (PyErr_WarnPy3k("f.xreadlines() not supported in 3.x, "
  1853. "try 'for line in f' instead", 1) < 0)
  1854. return NULL;
  1855. return file_self(f);
  1856. }
  1857. static PyObject *
  1858. file_exit(PyObject *f, PyObject *args)
  1859. {
  1860. PyObject *ret = PyObject_CallMethod(f, "close", NULL);
  1861. if (!ret)
  1862. /* If error occurred, pass through */
  1863. return NULL;
  1864. Py_DECREF(ret);
  1865. /* We cannot return the result of close since a true
  1866. * value will be interpreted as "yes, swallow the
  1867. * exception if one was raised inside the with block". */
  1868. Py_RETURN_NONE;
  1869. }
  1870. PyDoc_STRVAR(readline_doc,
  1871. "readline([size]) -> next line from the file, as a string.\n"
  1872. "\n"
  1873. "Retain newline. A non-negative size argument limits the maximum\n"
  1874. "number of bytes to return (an incomplete line may be returned then).\n"
  1875. "Return an empty string at EOF.");
  1876. PyDoc_STRVAR(read_doc,
  1877. "read([size]) -> read at most size bytes, returned as a string.\n"
  1878. "\n"
  1879. "If the size argument is negative or omitted, read until EOF is reached.\n"
  1880. "Notice that when in non-blocking mode, less data than what was requested\n"
  1881. "may be returned, even if no size parameter was given.");
  1882. PyDoc_STRVAR(write_doc,
  1883. "write(str) -> None. Write string str to file.\n"
  1884. "\n"
  1885. "Note that due to buffering, flush() or close() may be needed before\n"
  1886. "the file on disk reflects the data written.");
  1887. PyDoc_STRVAR(fileno_doc,
  1888. "fileno() -> integer \"file descriptor\".\n"
  1889. "\n"
  1890. "This is needed for lower-level file interfaces, such os.read().");
  1891. PyDoc_STRVAR(seek_doc,
  1892. "seek(offset[, whence]) -> None. Move to new file position.\n"
  1893. "\n"
  1894. "Argument offset is a byte count. Optional argument whence defaults to\n"
  1895. "0 (offset from start of file, offset should be >= 0); other values are 1\n"
  1896. "(move relative to current position, positive or negative), and 2 (move\n"
  1897. "relative to end of file, usually negative, although many platforms allow\n"
  1898. "seeking beyond the end of a file). If the file is opened in text mode,\n"
  1899. "only offsets returned by tell() are legal. Use of other offsets causes\n"
  1900. "undefined behavior."
  1901. "\n"
  1902. "Note that not all file objects are seekable.");
  1903. #ifdef HAVE_FTRUNCATE
  1904. PyDoc_STRVAR(truncate_doc,
  1905. "truncate([size]) -> None. Truncate the file to at most size bytes.\n"
  1906. "\n"
  1907. "Size defaults to the current file position, as returned by tell().");
  1908. #endif
  1909. PyDoc_STRVAR(tell_doc,
  1910. "tell() -> current file position, an integer (may be a long integer).");
  1911. PyDoc_STRVAR(readinto_doc,
  1912. "readinto() -> Undocumented. Don't use this; it may go away.");
  1913. PyDoc_STRVAR(readlines_doc,
  1914. "readlines([size]) -> list of strings, each a line from the file.\n"
  1915. "\n"
  1916. "Call readline() repeatedly and return a list of the lines so read.\n"
  1917. "The optional size argument, if given, is an approximate bound on the\n"
  1918. "total number of bytes in the lines returned.");
  1919. PyDoc_STRVAR(xreadlines_doc,
  1920. "xreadlines() -> returns self.\n"
  1921. "\n"
  1922. "For backward compatibility. File objects now include the performance\n"
  1923. "optimizations previously implemented in the xreadlines module.");
  1924. PyDoc_STRVAR(writelines_doc,
  1925. "writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
  1926. "\n"
  1927. "Note that newlines are not added. The sequence can be any iterable object\n"
  1928. "producing strings. This is equivalent to calling write() for each string.");
  1929. PyDoc_STRVAR(flush_doc,
  1930. "flush() -> None. Flush the internal I/O buffer.");
  1931. PyDoc_STRVAR(close_doc,
  1932. "close() -> None or (perhaps) an integer. Close the file.\n"
  1933. "\n"
  1934. "Sets data attribute .closed to True. A closed file cannot be used for\n"
  1935. "further I/O operations. close() may be called more than once without\n"
  1936. "error. Some kinds of file objects (for example, opened by popen())\n"
  1937. "may return an exit status upon closing.");
  1938. PyDoc_STRVAR(isatty_doc,
  1939. "isatty() -> true or false. True if the file is connected to a tty device.");
  1940. PyDoc_STRVAR(enter_doc,
  1941. "__enter__() -> self.");
  1942. PyDoc_STRVAR(exit_doc,
  1943. "__exit__(*excinfo) -> None. Closes the file.");
  1944. static PyMethodDef file_methods[] = {
  1945. {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
  1946. {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
  1947. {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
  1948. {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
  1949. {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
  1950. #ifdef HAVE_FTRUNCATE
  1951. {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
  1952. #endif
  1953. {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
  1954. {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
  1955. {"readlines", (PyCFunction)file_readlines, METH_VARARGS, readlines_doc},
  1956. {"xreadlines",(PyCFunction)file_xreadlines, METH_NOARGS, xreadlines_doc},
  1957. {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
  1958. {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
  1959. {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
  1960. {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
  1961. {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
  1962. {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
  1963. {NULL, NULL} /* sentinel */
  1964. };
  1965. #define OFF(x) offsetof(PyFileObject, x)
  1966. static PyMemberDef file_memberlist[] = {
  1967. {"mode", T_OBJECT, OFF(f_mode), RO,
  1968. "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
  1969. {"name", T_OBJECT, OFF(f_name), RO,
  1970. "file name"},
  1971. {"encoding", T_OBJECT, OFF(f_encoding), RO,
  1972. "file encoding"},
  1973. {"errors", T_OBJECT, OFF(f_errors), RO,
  1974. "Unicode error handler"},
  1975. /* getattr(f, "closed") is implemented without this table */
  1976. {NULL} /* Sentinel */
  1977. };
  1978. static PyObject *
  1979. get_closed(PyFileObject *f, void *closure)
  1980. {
  1981. return PyBool_FromLong((long)(f->f_fp == 0));
  1982. }
  1983. static PyObject *
  1984. get_newlines(PyFileObject *f, void *closure)
  1985. {
  1986. switch (f->f_newlinetypes) {
  1987. case NEWLINE_UNKNOWN:
  1988. Py_INCREF(Py_None);
  1989. return Py_None;
  1990. case NEWLINE_CR:
  1991. return PyString_FromString("\r");
  1992. case NEWLINE_LF:
  1993. return PyString_FromString("\n");
  1994. case NEWLINE_CR|NEWLINE_LF:
  1995. return Py_BuildValue("(ss)", "\r", "\n");
  1996. case NEWLINE_CRLF:
  1997. return PyString_FromString("\r\n");
  1998. case NEWLINE_CR|NEWLINE_CRLF:
  1999. return Py_BuildValue("(ss)", "\r", "\r\n");
  2000. case NEWLINE_LF|NEWLINE_CRLF:
  2001. return Py_BuildValue("(ss)", "\n", "\r\n");
  2002. case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
  2003. return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
  2004. default:
  2005. PyErr_Format(PyExc_SystemError,
  2006. "Unknown newlines value 0x%x\n",
  2007. f->f_newlinetypes);
  2008. return NULL;
  2009. }
  2010. }
  2011. static PyObject *
  2012. get_softspace(PyFileObject *f, void *closure)
  2013. {
  2014. if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
  2015. return NULL;
  2016. return PyInt_FromLong(f->f_softspace);
  2017. }
  2018. static int
  2019. set_softspace(PyFileObject *f, PyObject *value)
  2020. {
  2021. int new;
  2022. if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
  2023. return -1;
  2024. if (value == NULL) {
  2025. PyErr_SetString(PyExc_TypeError,
  2026. "can't delete softspace attribute");
  2027. return -1;
  2028. }
  2029. new = PyInt_AsLong(value);
  2030. if (new == -1 && PyErr_Occurred())
  2031. return -1;
  2032. f->f_softspace = new;
  2033. return 0;
  2034. }
  2035. static PyGetSetDef file_getsetlist[] = {
  2036. {"closed", (getter)get_closed, NULL, "True if the file is closed"},
  2037. {"newlines", (getter)get_newlines, NULL,
  2038. "end-of-line convention used in this file"},
  2039. {"softspace", (getter)get_softspace, (setter)set_softspace,
  2040. "flag indicating that a space needs to be printed; used by print"},
  2041. {0},
  2042. };
  2043. static void
  2044. drop_readahead(PyFileObject *f)
  2045. {
  2046. if (f->f_buf != NULL) {
  2047. PyMem_Free(f->f_buf);
  2048. f->f_buf = NULL;
  2049. }
  2050. }
  2051. /* Make sure that file has a readahead buffer with at least one byte
  2052. (unless at EOF) and no more than bufsize. Returns negative value on
  2053. error, will set MemoryError if bufsize bytes cannot be allocated. */
  2054. static int
  2055. readahead(PyFileObject *f, int bufsize)
  2056. {
  2057. Py_ssize_t chunksize;
  2058. if (f->f_buf != NULL) {
  2059. if( (f->f_bufend - f->f_bufptr) >= 1)
  2060. return 0;
  2061. else
  2062. drop_readahead(f);
  2063. }
  2064. if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
  2065. PyErr_NoMemory();
  2066. return -1;
  2067. }
  2068. FILE_BEGIN_ALLOW_THREADS(f)
  2069. errno = 0;
  2070. chunksize = Py_UniversalNewlineFread(
  2071. f->f_buf, bufsize, f->f_fp, (PyObject *)f);
  2072. FILE_END_ALLOW_THREADS(f)
  2073. if (chunksize == 0) {
  2074. if (ferror(f->f_fp)) {
  2075. PyErr_SetFromErrno(PyExc_IOError);
  2076. clearerr(f->f_fp);
  2077. drop_readahead(f);
  2078. return -1;
  2079. }
  2080. }
  2081. f->f_bufptr = f->f_buf;
  2082. f->f_bufend = f->f_buf + chunksize;
  2083. return 0;
  2084. }
  2085. /* Used by file_iternext. The returned string will start with 'skip'
  2086. uninitialized bytes followed by the remainder of the line. Don't be
  2087. horrified by the recursive call: maximum recursion depth is limited by
  2088. logarithmic buffer growth to about 50 even when reading a 1gb line. */
  2089. static PyStringObject *
  2090. readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
  2091. {
  2092. PyStringObject* s;
  2093. char *bufptr;
  2094. char *buf;
  2095. Py_ssize_t len;
  2096. if (f->f_buf == NULL)
  2097. if (readahead(f, bufsize) < 0)
  2098. return NULL;
  2099. len = f->f_bufend - f->f_bufptr;
  2100. if (len == 0)
  2101. return (PyStringObject *)
  2102. PyString_FromStringAndSize(NULL, skip);
  2103. bufptr = (char *)memchr(f->f_bufptr, '\n', len);
  2104. if (bufptr != NULL) {
  2105. bufptr++; /* Count the '\n' */
  2106. len = bufptr - f->f_bufptr;
  2107. s = (PyStringObject *)
  2108. PyString_FromStringAndSize(NULL, skip+len);
  2109. if (s == NULL)
  2110. return NULL;
  2111. memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
  2112. f->f_bufptr = bufptr;
  2113. if (bufptr == f->f_bufend)
  2114. drop_readahead(f);
  2115. } else {
  2116. bufptr = f->f_bufptr;
  2117. buf = f->f_buf;
  2118. f->f_buf = NULL; /* Force new readahead buffer */
  2119. assert(skip+len < INT_MAX);
  2120. s = readahead_get_line_skip(
  2121. f, (int)(skip+len), bufsize + (bufsize>>2) );
  2122. if (s == NULL) {
  2123. PyMem_Free(buf);
  2124. return NULL;
  2125. }
  2126. memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
  2127. PyMem_Free(buf);
  2128. }
  2129. return s;
  2130. }
  2131. /* A larger buffer size may actually decrease performance. */
  2132. #define READAHEAD_BUFSIZE 8192
  2133. static PyObject *
  2134. file_iternext(PyFileObject *f)
  2135. {
  2136. PyStringObject* l;
  2137. if (f->f_fp == NULL)
  2138. return err_closed();
  2139. if (!f->readable)
  2140. return err_mode("reading");
  2141. l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
  2142. if (l == NULL || PyString_GET_SIZE(l) == 0) {
  2143. Py_XDECREF(l);
  2144. return NULL;
  2145. }
  2146. return (PyObject *)l;
  2147. }
  2148. static PyObject *
  2149. file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  2150. {
  2151. PyObject *self;
  2152. static PyObject *not_yet_string;
  2153. assert(type != NULL && type->tp_alloc != NULL);
  2154. if (not_yet_string == NULL) {
  2155. not_yet_string = PyString_InternFromString("<uninitialized file>");
  2156. if (not_yet_string == NULL)
  2157. return NULL;
  2158. }
  2159. self = type->tp_alloc(type, 0);
  2160. if (self != NULL) {
  2161. /* Always fill in the name and mode, so that nobody else
  2162. needs to special-case NULLs there. */
  2163. Py_INCREF(not_yet_string);
  2164. ((PyFileObject *)self)->f_name = not_yet_string;
  2165. Py_INCREF(not_yet_string);
  2166. ((PyFileObject *)self)->f_mode = not_yet_string;
  2167. Py_INCREF(Py_None);
  2168. ((PyFileObject *)self)->f_encoding = Py_None;
  2169. Py_INCREF(Py_None);
  2170. ((PyFileObject *)self)->f_errors = Py_None;
  2171. ((PyFileObject *)self)->weakreflist = NULL;
  2172. ((PyFileObject *)self)->unlocked_count = 0;
  2173. }
  2174. return self;
  2175. }
  2176. static int
  2177. file_init(PyObject *self, PyObject *args, PyObject *kwds)
  2178. {
  2179. PyFileObject *foself = (PyFileObject *)self;
  2180. int ret = 0;
  2181. static char *kwlist[] = {"name", "mode", "buffering", 0};
  2182. char *name = NULL;
  2183. char *mode = "r";
  2184. int bufsize = -1;
  2185. int wideargument = 0;
  2186. #ifdef MS_WINDOWS
  2187. PyObject *po;
  2188. #endif
  2189. assert(PyFile_Check(self));
  2190. if (foself->f_fp != NULL) {
  2191. /* Have to close the existing file first. */
  2192. PyObject *closeresult = file_close(foself);
  2193. if (closeresult == NULL)
  2194. return -1;
  2195. Py_DECREF(closeresult);
  2196. }
  2197. #ifdef MS_WINDOWS
  2198. if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
  2199. kwlist, &po, &mode, &bufsize)) {
  2200. wideargument = 1;
  2201. if (fill_file_fields(foself, NULL, po, mode,
  2202. fclose) == NULL)
  2203. goto Error;
  2204. } else {
  2205. /* Drop the argument parsing error as narrow
  2206. strings are also valid. */
  2207. PyErr_Clear();
  2208. }
  2209. #endif
  2210. if (!wideargument) {
  2211. PyObject *o_name;
  2212. if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
  2213. Py_FileSystemDefaultEncoding,
  2214. &name,
  2215. &mode, &bufsize))
  2216. return -1;
  2217. /* We parse again to get the name as a PyObject */
  2218. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
  2219. kwlist, &o_name, &mode,
  2220. &bufsize))
  2221. goto Error;
  2222. if (fill_file_fields(foself, NULL, o_name, mode,
  2223. fclose) == NULL)
  2224. goto Error;
  2225. }
  2226. if (open_the_file(foself, name, mode) == NULL)
  2227. goto Error;
  2228. foself->f_setbuf = NULL;
  2229. PyFile_SetBufSize(self, bufsize);
  2230. goto Done;
  2231. Error:
  2232. ret = -1;
  2233. /* fall through */
  2234. Done:
  2235. PyMem_Free(name); /* free the encoded string */
  2236. return ret;
  2237. }
  2238. PyDoc_VAR(file_doc) =
  2239. PyDoc_STR(
  2240. "file(name[, mode[, buffering]]) -> file object\n"
  2241. "\n"
  2242. "Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
  2243. "writing or appending. The file will be created if it doesn't exist\n"
  2244. "when opened for writing or appending; it will be truncated when\n"
  2245. "opened for writing. Add a 'b' to the mode for binary files.\n"
  2246. "Add a '+' to the mode to allow simultaneous reading and writing.\n"
  2247. "If the buffering argument is given, 0 means unbuffered, 1 means line\n"
  2248. "buffered, and larger numbers specify the buffer size. The preferred way\n"
  2249. "to open a file is with the builtin open() function.\n"
  2250. )
  2251. PyDoc_STR(
  2252. "Add a 'U' to mode to open the file for input with universal newline\n"
  2253. "support. Any line ending in the input file will be seen as a '\\n'\n"
  2254. "in Python. Also, a file so opened gains the attribute 'newlines';\n"
  2255. "the value for this attribute is one of None (no newline read yet),\n"
  2256. "'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
  2257. "\n"
  2258. "'U' cannot be combined with 'w' or '+' mode.\n"
  2259. );
  2260. PyTypeObject PyFile_Type = {
  2261. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  2262. "file",
  2263. sizeof(PyFileObject),
  2264. 0,
  2265. (destructor)file_dealloc, /* tp_dealloc */
  2266. 0, /* tp_print */
  2267. 0, /* tp_getattr */
  2268. 0, /* tp_setattr */
  2269. 0, /* tp_compare */
  2270. (reprfunc)file_repr, /* tp_repr */
  2271. 0, /* tp_as_number */
  2272. 0, /* tp_as_sequence */
  2273. 0, /* tp_as_mapping */
  2274. 0, /* tp_hash */
  2275. 0, /* tp_call */
  2276. 0, /* tp_str */
  2277. PyObject_GenericGetAttr, /* tp_getattro */
  2278. /* softspace is writable: we must supply tp_setattro */
  2279. PyObject_GenericSetAttr, /* tp_setattro */
  2280. 0, /* tp_as_buffer */
  2281. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
  2282. file_doc, /* tp_doc */
  2283. 0, /* tp_traverse */
  2284. 0, /* tp_clear */
  2285. 0, /* tp_richcompare */
  2286. offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
  2287. (getiterfunc)file_self, /* tp_iter */
  2288. (iternextfunc)file_iternext, /* tp_iternext */
  2289. file_methods, /* tp_methods */
  2290. file_memberlist, /* tp_members */
  2291. file_getsetlist, /* tp_getset */
  2292. 0, /* tp_base */
  2293. 0, /* tp_dict */
  2294. 0, /* tp_descr_get */
  2295. 0, /* tp_descr_set */
  2296. 0, /* tp_dictoffset */
  2297. file_init, /* tp_init */
  2298. PyType_GenericAlloc, /* tp_alloc */
  2299. file_new, /* tp_new */
  2300. PyObject_Del, /* tp_free */
  2301. };
  2302. /* Interface for the 'soft space' between print items. */
  2303. int
  2304. PyFile_SoftSpace(PyObject *f, int newflag)
  2305. {
  2306. long oldflag = 0;
  2307. if (f == NULL) {
  2308. /* Do nothing */
  2309. }
  2310. else if (PyFile_Check(f)) {
  2311. oldflag = ((PyFileObject *)f)->f_softspace;
  2312. ((PyFileObject *)f)->f_softspace = newflag;
  2313. }
  2314. else {
  2315. PyObject *v;
  2316. v = PyObject_GetAttrString(f, "softspace");
  2317. if (v == NULL)
  2318. PyErr_Clear();
  2319. else {
  2320. if (PyInt_Check(v))
  2321. oldflag = PyInt_AsLong(v);
  2322. assert(oldflag < INT_MAX);
  2323. Py_DECREF(v);
  2324. }
  2325. v = PyInt_FromLong((long)newflag);
  2326. if (v == NULL)
  2327. PyErr_Clear();
  2328. else {
  2329. if (PyObject_SetAttrString(f, "softspace", v) != 0)
  2330. PyErr_Clear();
  2331. Py_DECREF(v);
  2332. }
  2333. }
  2334. return (int)oldflag;
  2335. }
  2336. /* Interfaces to write objects/strings to file-like objects */
  2337. int
  2338. PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
  2339. {
  2340. PyObject *writer, *value, *args, *result;
  2341. if (f == NULL) {
  2342. PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
  2343. return -1;
  2344. }
  2345. else if (PyFile_Check(f)) {
  2346. PyFileObject *fobj = (PyFileObject *) f;
  2347. #ifdef Py_USING_UNICODE
  2348. PyObject *enc = fobj->f_encoding;
  2349. int result;
  2350. #endif
  2351. if (fobj->f_fp == NULL) {
  2352. err_closed();
  2353. return -1;
  2354. }
  2355. #ifdef Py_USING_UNICODE
  2356. if ((flags & Py_PRINT_RAW) &&
  2357. PyUnicode_Check(v) && enc != Py_None) {
  2358. char *cenc = PyString_AS_STRING(enc);
  2359. char *errors = fobj->f_errors == Py_None ?
  2360. "strict" : PyString_AS_STRING(fobj->f_errors);
  2361. value = PyUnicode_AsEncodedString(v, cenc, errors);
  2362. if (value == NULL)
  2363. return -1;
  2364. } else {
  2365. value = v;
  2366. Py_INCREF(value);
  2367. }
  2368. result = file_PyObject_Print(value, fobj, flags);
  2369. Py_DECREF(value);
  2370. return result;
  2371. #else
  2372. return file_PyObject_Print(v, fobj, flags);
  2373. #endif
  2374. }
  2375. writer = PyObject_GetAttrString(f, "write");
  2376. if (writer == NULL)
  2377. return -1;
  2378. if (flags & Py_PRINT_RAW) {
  2379. if (PyUnicode_Check(v)) {
  2380. value = v;
  2381. Py_INCREF(value);
  2382. } else
  2383. value = PyObject_Str(v);
  2384. }
  2385. else
  2386. value = PyObject_Repr(v);
  2387. if (value == NULL) {
  2388. Py_DECREF(writer);
  2389. return -1;
  2390. }
  2391. args = PyTuple_Pack(1, value);
  2392. if (args == NULL) {
  2393. Py_DECREF(value);
  2394. Py_DECREF(writer);
  2395. return -1;
  2396. }
  2397. result = PyEval_CallObject(writer, args);
  2398. Py_DECREF(args);
  2399. Py_DECREF(value);
  2400. Py_DECREF(writer);
  2401. if (result == NULL)
  2402. return -1;
  2403. Py_DECREF(result);
  2404. return 0;
  2405. }
  2406. int
  2407. PyFile_WriteString(const char *s, PyObject *f)
  2408. {
  2409. if (f == NULL) {
  2410. /* Should be caused by a pre-existing error */
  2411. if (!PyErr_Occurred())
  2412. PyErr_SetString(PyExc_SystemError,
  2413. "null file for PyFile_WriteString");
  2414. return -1;
  2415. }
  2416. else if (PyFile_Check(f)) {
  2417. PyFileObject *fobj = (PyFileObject *) f;
  2418. FILE *fp = PyFile_AsFile(f);
  2419. if (fp == NULL) {
  2420. err_closed();
  2421. return -1;
  2422. }
  2423. FILE_BEGIN_ALLOW_THREADS(fobj)
  2424. fputs(s, fp);
  2425. FILE_END_ALLOW_THREADS(fobj)
  2426. return 0;
  2427. }
  2428. else if (!PyErr_Occurred()) {
  2429. PyObject *v = PyString_FromString(s);
  2430. int err;
  2431. if (v == NULL)
  2432. return -1;
  2433. err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
  2434. Py_DECREF(v);
  2435. return err;
  2436. }
  2437. else
  2438. return -1;
  2439. }
  2440. /* Try to get a file-descriptor from a Python object. If the object
  2441. is an integer or long integer, its value is returned. If not, the
  2442. object's fileno() method is called if it exists; the method must return
  2443. an integer or long integer, which is returned as the file descriptor value.
  2444. -1 is returned on failure.
  2445. */
  2446. int PyObject_AsFileDescriptor(PyObject *o)
  2447. {
  2448. int fd;
  2449. PyObject *meth;
  2450. if (PyInt_Check(o)) {
  2451. fd = PyInt_AsLong(o);
  2452. }
  2453. else if (PyLong_Check(o)) {
  2454. fd = PyLong_AsLong(o);
  2455. }
  2456. else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
  2457. {
  2458. PyObject *fno = PyEval_CallObject(meth, NULL);
  2459. Py_DECREF(meth);
  2460. if (fno == NULL)
  2461. return -1;
  2462. if (PyInt_Check(fno)) {
  2463. fd = PyInt_AsLong(fno);
  2464. Py_DECREF(fno);
  2465. }
  2466. else if (PyLong_Check(fno)) {
  2467. fd = PyLong_AsLong(fno);
  2468. Py_DECREF(fno);
  2469. }
  2470. else {
  2471. PyErr_SetString(PyExc_TypeError,
  2472. "fileno() returned a non-integer");
  2473. Py_DECREF(fno);
  2474. return -1;
  2475. }
  2476. }
  2477. else {
  2478. PyErr_SetString(PyExc_TypeError,
  2479. "argument must be an int, or have a fileno() method.");
  2480. return -1;
  2481. }
  2482. if (fd < 0) {
  2483. PyErr_Format(PyExc_ValueError,
  2484. "file descriptor cannot be a negative integer (%i)",
  2485. fd);
  2486. return -1;
  2487. }
  2488. return fd;
  2489. }
  2490. /* From here on we need access to the real fgets and fread */
  2491. #undef fgets
  2492. #undef fread
  2493. /*
  2494. ** Py_UniversalNewlineFgets is an fgets variation that understands
  2495. ** all of \r, \n and \r\n conventions.
  2496. ** The stream should be opened in binary mode.
  2497. ** If fobj is NULL the routine always does newline conversion, and
  2498. ** it may peek one char ahead to gobble the second char in \r\n.
  2499. ** If fobj is non-NULL it must be a PyFileObject. In this case there
  2500. ** is no readahead but in stead a flag is used to skip a following
  2501. ** \n on the next read. Also, if the file is open in binary mode
  2502. ** the whole conversion is skipped. Finally, the routine keeps track of
  2503. ** the different types of newlines seen.
  2504. ** Note that we need no error handling: fgets() treats error and eof
  2505. ** identically.
  2506. */
  2507. char *
  2508. Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
  2509. {
  2510. char *p = buf;
  2511. int c;
  2512. int newlinetypes = 0;
  2513. int skipnextlf = 0;
  2514. int univ_newline = 1;
  2515. if (fobj) {
  2516. if (!PyFile_Check(fobj)) {
  2517. errno = ENXIO; /* What can you do... */
  2518. return NULL;
  2519. }
  2520. univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
  2521. if ( !univ_newline )
  2522. return fgets(buf, n, stream);
  2523. newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
  2524. skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
  2525. }
  2526. FLOCKFILE(stream);
  2527. c = 'x'; /* Shut up gcc warning */
  2528. while (--n > 0 && (c = GETC(stream)) != EOF ) {
  2529. if (skipnextlf ) {
  2530. skipnextlf = 0;
  2531. if (c == '\n') {
  2532. /* Seeing a \n here with skipnextlf true
  2533. ** means we saw a \r before.
  2534. */
  2535. newlinetypes |= NEWLINE_CRLF;
  2536. c = GETC(stream);
  2537. if (c == EOF) break;
  2538. } else {
  2539. /*
  2540. ** Note that c == EOF also brings us here,
  2541. ** so we're okay if the last char in the file
  2542. ** is a CR.
  2543. */
  2544. newlinetypes |= NEWLINE_CR;
  2545. }
  2546. }
  2547. if (c == '\r') {
  2548. /* A \r is translated into a \n, and we skip
  2549. ** an adjacent \n, if any. We don't set the
  2550. ** newlinetypes flag until we've seen the next char.
  2551. */
  2552. skipnextlf = 1;
  2553. c = '\n';
  2554. } else if ( c == '\n') {
  2555. newlinetypes |= NEWLINE_LF;
  2556. }
  2557. *p++ = c;
  2558. if (c == '\n') break;
  2559. }
  2560. if ( c == EOF && skipnextlf )
  2561. newlinetypes |= NEWLINE_CR;
  2562. FUNLOCKFILE(stream);
  2563. *p = '\0';
  2564. if (fobj) {
  2565. ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
  2566. ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
  2567. } else if ( skipnextlf ) {
  2568. /* If we have no file object we cannot save the
  2569. ** skipnextlf flag. We have to readahead, which
  2570. ** will cause a pause if we're reading from an
  2571. ** interactive stream, but that is very unlikely
  2572. ** unless we're doing something silly like
  2573. ** execfile("/dev/tty").
  2574. */
  2575. c = GETC(stream);
  2576. if ( c != '\n' )
  2577. ungetc(c, stream);
  2578. }
  2579. if (p == buf)
  2580. return NULL;
  2581. return buf;
  2582. }
  2583. /*
  2584. ** Py_UniversalNewlineFread is an fread variation that understands
  2585. ** all of \r, \n and \r\n conventions.
  2586. ** The stream should be opened in binary mode.
  2587. ** fobj must be a PyFileObject. In this case there
  2588. ** is no readahead but in stead a flag is used to skip a following
  2589. ** \n on the next read. Also, if the file is open in binary mode
  2590. ** the whole conversion is skipped. Finally, the routine keeps track of
  2591. ** the different types of newlines seen.
  2592. */
  2593. size_t
  2594. Py_UniversalNewlineFread(char *buf, size_t n,
  2595. FILE *stream, PyObject *fobj)
  2596. {
  2597. char *dst = buf;
  2598. PyFileObject *f = (PyFileObject *)fobj;
  2599. int newlinetypes, skipnextlf;
  2600. assert(buf != NULL);
  2601. assert(stream != NULL);
  2602. if (!fobj || !PyFile_Check(fobj)) {
  2603. errno = ENXIO; /* What can you do... */
  2604. return 0;
  2605. }
  2606. if (!f->f_univ_newline)
  2607. return fread(buf, 1, n, stream);
  2608. newlinetypes = f->f_newlinetypes;
  2609. skipnextlf = f->f_skipnextlf;
  2610. /* Invariant: n is the number of bytes remaining to be filled
  2611. * in the buffer.
  2612. */
  2613. while (n) {
  2614. size_t nread;
  2615. int shortread;
  2616. char *src = dst;
  2617. nread = fread(dst, 1, n, stream);
  2618. assert(nread <= n);
  2619. if (nread == 0)
  2620. break;
  2621. n -= nread; /* assuming 1 byte out for each in; will adjust */
  2622. shortread = n != 0; /* true iff EOF or error */
  2623. while (nread--) {
  2624. char c = *src++;
  2625. if (c == '\r') {
  2626. /* Save as LF and set flag to skip next LF. */
  2627. *dst++ = '\n';
  2628. skipnextlf = 1;
  2629. }
  2630. else if (skipnextlf && c == '\n') {
  2631. /* Skip LF, and remember we saw CR LF. */
  2632. skipnextlf = 0;
  2633. newlinetypes |= NEWLINE_CRLF;
  2634. ++n;
  2635. }
  2636. else {
  2637. /* Normal char to be stored in buffer. Also
  2638. * update the newlinetypes flag if either this
  2639. * is an LF or the previous char was a CR.
  2640. */
  2641. if (c == '\n')
  2642. newlinetypes |= NEWLINE_LF;
  2643. else if (skipnextlf)
  2644. newlinetypes |= NEWLINE_CR;
  2645. *dst++ = c;
  2646. skipnextlf = 0;
  2647. }
  2648. }
  2649. if (shortread) {
  2650. /* If this is EOF, update type flags. */
  2651. if (skipnextlf && feof(stream))
  2652. newlinetypes |= NEWLINE_CR;
  2653. break;
  2654. }
  2655. }
  2656. f->f_newlinetypes = newlinetypes;
  2657. f->f_skipnextlf = skipnextlf;
  2658. return dst - buf;
  2659. }
  2660. #ifdef __cplusplus
  2661. }
  2662. #endif