PageRenderTime 59ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/Objects/fileobject.c

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