iobase.c 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  1. /*
  2. An implementation of the I/O abstract base classes hierarchy
  3. as defined by PEP 3116 - "New I/O"
  4. Classes defined here: IOBase, RawIOBase.
  5. Written by Amaury Forgeot d'Arc and Antoine Pitrou
  6. */
  7. #define PY_SSIZE_T_CLEAN
  8. #include "Python.h"
  9. #include "pycore_long.h" // _PyLong_GetOne()
  10. #include "pycore_object.h"
  11. #include <stddef.h> // offsetof()
  12. #include "_iomodule.h"
  13. /*[clinic input]
  14. module _io
  15. class _io._IOBase "PyObject *" "clinic_state()->PyIOBase_Type"
  16. class _io._RawIOBase "PyObject *" "clinic_state()->PyRawIOBase_Type"
  17. [clinic start generated code]*/
  18. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=9006b7802ab8ea85]*/
  19. /*
  20. * IOBase class, an abstract class
  21. */
  22. typedef struct {
  23. PyObject_HEAD
  24. PyObject *dict;
  25. PyObject *weakreflist;
  26. } iobase;
  27. PyDoc_STRVAR(iobase_doc,
  28. "The abstract base class for all I/O classes.\n"
  29. "\n"
  30. "This class provides dummy implementations for many methods that\n"
  31. "derived classes can override selectively; the default implementations\n"
  32. "represent a file that cannot be read, written or seeked.\n"
  33. "\n"
  34. "Even though IOBase does not declare read, readinto, or write because\n"
  35. "their signatures will vary, implementations and clients should\n"
  36. "consider those methods part of the interface. Also, implementations\n"
  37. "may raise UnsupportedOperation when operations they do not support are\n"
  38. "called.\n"
  39. "\n"
  40. "The basic type used for binary data read from or written to a file is\n"
  41. "bytes. Other bytes-like objects are accepted as method arguments too.\n"
  42. "In some cases (such as readinto), a writable object is required. Text\n"
  43. "I/O classes work with str data.\n"
  44. "\n"
  45. "Note that calling any method (except additional calls to close(),\n"
  46. "which are ignored) on a closed stream should raise a ValueError.\n"
  47. "\n"
  48. "IOBase (and its subclasses) support the iterator protocol, meaning\n"
  49. "that an IOBase object can be iterated over yielding the lines in a\n"
  50. "stream.\n"
  51. "\n"
  52. "IOBase also supports the :keyword:`with` statement. In this example,\n"
  53. "fp is closed after the suite of the with statement is complete:\n"
  54. "\n"
  55. "with open('spam.txt', 'r') as fp:\n"
  56. " fp.write('Spam and eggs!')\n");
  57. /* Use this macro whenever you want to check the internal `closed` status
  58. of the IOBase object rather than the virtual `closed` attribute as returned
  59. by whatever subclass. */
  60. /* Internal methods */
  61. static PyObject *
  62. iobase_unsupported(_PyIO_State *state, const char *message)
  63. {
  64. PyErr_SetString(state->unsupported_operation, message);
  65. return NULL;
  66. }
  67. /* Positioning */
  68. /*[clinic input]
  69. _io._IOBase.seek
  70. cls: defining_class
  71. offset: int(unused=True)
  72. The stream position, relative to 'whence'.
  73. whence: int(unused=True, c_default='0') = os.SEEK_SET
  74. The relative position to seek from.
  75. /
  76. Change the stream position to the given byte offset.
  77. The offset is interpreted relative to the position indicated by whence.
  78. Values for whence are:
  79. * os.SEEK_SET or 0 -- start of stream (the default); offset should be zero or positive
  80. * os.SEEK_CUR or 1 -- current stream position; offset may be negative
  81. * os.SEEK_END or 2 -- end of stream; offset is usually negative
  82. Return the new absolute position.
  83. [clinic start generated code]*/
  84. static PyObject *
  85. _io__IOBase_seek_impl(PyObject *self, PyTypeObject *cls,
  86. int Py_UNUSED(offset), int Py_UNUSED(whence))
  87. /*[clinic end generated code: output=8bd74ea6538ded53 input=74211232b363363e]*/
  88. {
  89. _PyIO_State *state = get_io_state_by_cls(cls);
  90. return iobase_unsupported(state, "seek");
  91. }
  92. /*[clinic input]
  93. _io._IOBase.tell
  94. Return current stream position.
  95. [clinic start generated code]*/
  96. static PyObject *
  97. _io__IOBase_tell_impl(PyObject *self)
  98. /*[clinic end generated code: output=89a1c0807935abe2 input=04e615fec128801f]*/
  99. {
  100. return _PyObject_CallMethod(self, &_Py_ID(seek), "ii", 0, 1);
  101. }
  102. /*[clinic input]
  103. _io._IOBase.truncate
  104. cls: defining_class
  105. size: object(unused=True) = None
  106. /
  107. Truncate file to size bytes.
  108. File pointer is left unchanged. Size defaults to the current IO position
  109. as reported by tell(). Return the new size.
  110. [clinic start generated code]*/
  111. static PyObject *
  112. _io__IOBase_truncate_impl(PyObject *self, PyTypeObject *cls,
  113. PyObject *Py_UNUSED(size))
  114. /*[clinic end generated code: output=2013179bff1fe8ef input=660ac20936612c27]*/
  115. {
  116. _PyIO_State *state = get_io_state_by_cls(cls);
  117. return iobase_unsupported(state, "truncate");
  118. }
  119. static int
  120. iobase_is_closed(PyObject *self)
  121. {
  122. PyObject *res;
  123. int ret;
  124. /* This gets the derived attribute, which is *not* __IOBase_closed
  125. in most cases! */
  126. ret = _PyObject_LookupAttr(self, &_Py_ID(__IOBase_closed), &res);
  127. Py_XDECREF(res);
  128. return ret;
  129. }
  130. /* Flush and close methods */
  131. /*[clinic input]
  132. _io._IOBase.flush
  133. Flush write buffers, if applicable.
  134. This is not implemented for read-only and non-blocking streams.
  135. [clinic start generated code]*/
  136. static PyObject *
  137. _io__IOBase_flush_impl(PyObject *self)
  138. /*[clinic end generated code: output=7cef4b4d54656a3b input=773be121abe270aa]*/
  139. {
  140. /* XXX Should this return the number of bytes written??? */
  141. int closed = iobase_is_closed(self);
  142. if (!closed) {
  143. Py_RETURN_NONE;
  144. }
  145. if (closed > 0) {
  146. PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
  147. }
  148. return NULL;
  149. }
  150. static PyObject *
  151. iobase_closed_get(PyObject *self, void *context)
  152. {
  153. int closed = iobase_is_closed(self);
  154. if (closed < 0) {
  155. return NULL;
  156. }
  157. return PyBool_FromLong(closed);
  158. }
  159. static int
  160. iobase_check_closed(PyObject *self)
  161. {
  162. PyObject *res;
  163. int closed;
  164. /* This gets the derived attribute, which is *not* __IOBase_closed
  165. in most cases! */
  166. closed = _PyObject_LookupAttr(self, &_Py_ID(closed), &res);
  167. if (closed > 0) {
  168. closed = PyObject_IsTrue(res);
  169. Py_DECREF(res);
  170. if (closed > 0) {
  171. PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
  172. return -1;
  173. }
  174. }
  175. return closed;
  176. }
  177. PyObject *
  178. _PyIOBase_check_closed(PyObject *self, PyObject *args)
  179. {
  180. if (iobase_check_closed(self)) {
  181. return NULL;
  182. }
  183. if (args == Py_True) {
  184. return Py_None;
  185. }
  186. Py_RETURN_NONE;
  187. }
  188. static PyObject *
  189. iobase_check_seekable(PyObject *self, PyObject *args)
  190. {
  191. _PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
  192. return _PyIOBase_check_seekable(state, self, args);
  193. }
  194. static PyObject *
  195. iobase_check_readable(PyObject *self, PyObject *args)
  196. {
  197. _PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
  198. return _PyIOBase_check_readable(state, self, args);
  199. }
  200. static PyObject *
  201. iobase_check_writable(PyObject *self, PyObject *args)
  202. {
  203. _PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
  204. return _PyIOBase_check_writable(state, self, args);
  205. }
  206. PyObject *
  207. _PyIOBase_cannot_pickle(PyObject *self, PyObject *args)
  208. {
  209. PyErr_Format(PyExc_TypeError,
  210. "cannot pickle '%.100s' instances", _PyType_Name(Py_TYPE(self)));
  211. return NULL;
  212. }
  213. /* XXX: IOBase thinks it has to maintain its own internal state in
  214. `__IOBase_closed` and call flush() by itself, but it is redundant with
  215. whatever behaviour a non-trivial derived class will implement. */
  216. /*[clinic input]
  217. _io._IOBase.close
  218. Flush and close the IO object.
  219. This method has no effect if the file is already closed.
  220. [clinic start generated code]*/
  221. static PyObject *
  222. _io__IOBase_close_impl(PyObject *self)
  223. /*[clinic end generated code: output=63c6a6f57d783d6d input=f4494d5c31dbc6b7]*/
  224. {
  225. int rc, closed = iobase_is_closed(self);
  226. if (closed < 0) {
  227. return NULL;
  228. }
  229. if (closed) {
  230. Py_RETURN_NONE;
  231. }
  232. PyObject *res = PyObject_CallMethodNoArgs(self, &_Py_ID(flush));
  233. PyObject *exc = PyErr_GetRaisedException();
  234. rc = PyObject_SetAttr(self, &_Py_ID(__IOBase_closed), Py_True);
  235. _PyErr_ChainExceptions1(exc);
  236. if (rc < 0) {
  237. Py_CLEAR(res);
  238. }
  239. if (res == NULL)
  240. return NULL;
  241. Py_DECREF(res);
  242. Py_RETURN_NONE;
  243. }
  244. /* Finalization and garbage collection support */
  245. static void
  246. iobase_finalize(PyObject *self)
  247. {
  248. PyObject *res;
  249. int closed;
  250. /* Save the current exception, if any. */
  251. PyObject *exc = PyErr_GetRaisedException();
  252. /* If `closed` doesn't exist or can't be evaluated as bool, then the
  253. object is probably in an unusable state, so ignore. */
  254. if (_PyObject_LookupAttr(self, &_Py_ID(closed), &res) <= 0) {
  255. PyErr_Clear();
  256. closed = -1;
  257. }
  258. else {
  259. closed = PyObject_IsTrue(res);
  260. Py_DECREF(res);
  261. if (closed == -1)
  262. PyErr_Clear();
  263. }
  264. if (closed == 0) {
  265. /* Signal close() that it was called as part of the object
  266. finalization process. */
  267. if (PyObject_SetAttr(self, &_Py_ID(_finalizing), Py_True))
  268. PyErr_Clear();
  269. res = PyObject_CallMethodNoArgs((PyObject *)self, &_Py_ID(close));
  270. /* Silencing I/O errors is bad, but printing spurious tracebacks is
  271. equally as bad, and potentially more frequent (because of
  272. shutdown issues). */
  273. if (res == NULL) {
  274. #ifndef Py_DEBUG
  275. if (_Py_GetConfig()->dev_mode) {
  276. PyErr_WriteUnraisable(self);
  277. }
  278. else {
  279. PyErr_Clear();
  280. }
  281. #else
  282. PyErr_WriteUnraisable(self);
  283. #endif
  284. }
  285. else {
  286. Py_DECREF(res);
  287. }
  288. }
  289. /* Restore the saved exception. */
  290. PyErr_SetRaisedException(exc);
  291. }
  292. int
  293. _PyIOBase_finalize(PyObject *self)
  294. {
  295. int is_zombie;
  296. /* If _PyIOBase_finalize() is called from a destructor, we need to
  297. resurrect the object as calling close() can invoke arbitrary code. */
  298. is_zombie = (Py_REFCNT(self) == 0);
  299. if (is_zombie)
  300. return PyObject_CallFinalizerFromDealloc(self);
  301. else {
  302. PyObject_CallFinalizer(self);
  303. return 0;
  304. }
  305. }
  306. static int
  307. iobase_traverse(iobase *self, visitproc visit, void *arg)
  308. {
  309. Py_VISIT(Py_TYPE(self));
  310. Py_VISIT(self->dict);
  311. return 0;
  312. }
  313. static int
  314. iobase_clear(iobase *self)
  315. {
  316. Py_CLEAR(self->dict);
  317. return 0;
  318. }
  319. /* Destructor */
  320. static void
  321. iobase_dealloc(iobase *self)
  322. {
  323. /* NOTE: since IOBaseObject has its own dict, Python-defined attributes
  324. are still available here for close() to use.
  325. However, if the derived class declares a __slots__, those slots are
  326. already gone.
  327. */
  328. if (_PyIOBase_finalize((PyObject *) self) < 0) {
  329. /* When called from a heap type's dealloc, the type will be
  330. decref'ed on return (see e.g. subtype_dealloc in typeobject.c). */
  331. if (_PyType_HasFeature(Py_TYPE(self), Py_TPFLAGS_HEAPTYPE)) {
  332. Py_INCREF(Py_TYPE(self));
  333. }
  334. return;
  335. }
  336. PyTypeObject *tp = Py_TYPE(self);
  337. _PyObject_GC_UNTRACK(self);
  338. if (self->weakreflist != NULL)
  339. PyObject_ClearWeakRefs((PyObject *) self);
  340. Py_CLEAR(self->dict);
  341. tp->tp_free((PyObject *)self);
  342. Py_DECREF(tp);
  343. }
  344. /* Inquiry methods */
  345. /*[clinic input]
  346. _io._IOBase.seekable
  347. Return whether object supports random access.
  348. If False, seek(), tell() and truncate() will raise OSError.
  349. This method may need to do a test seek().
  350. [clinic start generated code]*/
  351. static PyObject *
  352. _io__IOBase_seekable_impl(PyObject *self)
  353. /*[clinic end generated code: output=4c24c67f5f32a43d input=b976622f7fdf3063]*/
  354. {
  355. Py_RETURN_FALSE;
  356. }
  357. PyObject *
  358. _PyIOBase_check_seekable(_PyIO_State *state, PyObject *self, PyObject *args)
  359. {
  360. PyObject *res = PyObject_CallMethodNoArgs(self, &_Py_ID(seekable));
  361. if (res == NULL)
  362. return NULL;
  363. if (res != Py_True) {
  364. Py_CLEAR(res);
  365. iobase_unsupported(state, "File or stream is not seekable.");
  366. return NULL;
  367. }
  368. if (args == Py_True) {
  369. Py_DECREF(res);
  370. }
  371. return res;
  372. }
  373. /*[clinic input]
  374. _io._IOBase.readable
  375. Return whether object was opened for reading.
  376. If False, read() will raise OSError.
  377. [clinic start generated code]*/
  378. static PyObject *
  379. _io__IOBase_readable_impl(PyObject *self)
  380. /*[clinic end generated code: output=e48089250686388b input=285b3b866a0ec35f]*/
  381. {
  382. Py_RETURN_FALSE;
  383. }
  384. /* May be called with any object */
  385. PyObject *
  386. _PyIOBase_check_readable(_PyIO_State *state, PyObject *self, PyObject *args)
  387. {
  388. PyObject *res = PyObject_CallMethodNoArgs(self, &_Py_ID(readable));
  389. if (res == NULL)
  390. return NULL;
  391. if (res != Py_True) {
  392. Py_CLEAR(res);
  393. iobase_unsupported(state, "File or stream is not readable.");
  394. return NULL;
  395. }
  396. if (args == Py_True) {
  397. Py_DECREF(res);
  398. }
  399. return res;
  400. }
  401. /*[clinic input]
  402. _io._IOBase.writable
  403. Return whether object was opened for writing.
  404. If False, write() will raise OSError.
  405. [clinic start generated code]*/
  406. static PyObject *
  407. _io__IOBase_writable_impl(PyObject *self)
  408. /*[clinic end generated code: output=406001d0985be14f input=9dcac18a013a05b5]*/
  409. {
  410. Py_RETURN_FALSE;
  411. }
  412. /* May be called with any object */
  413. PyObject *
  414. _PyIOBase_check_writable(_PyIO_State *state, PyObject *self, PyObject *args)
  415. {
  416. PyObject *res = PyObject_CallMethodNoArgs(self, &_Py_ID(writable));
  417. if (res == NULL)
  418. return NULL;
  419. if (res != Py_True) {
  420. Py_CLEAR(res);
  421. iobase_unsupported(state, "File or stream is not writable.");
  422. return NULL;
  423. }
  424. if (args == Py_True) {
  425. Py_DECREF(res);
  426. }
  427. return res;
  428. }
  429. /* Context manager */
  430. static PyObject *
  431. iobase_enter(PyObject *self, PyObject *args)
  432. {
  433. if (iobase_check_closed(self))
  434. return NULL;
  435. return Py_NewRef(self);
  436. }
  437. static PyObject *
  438. iobase_exit(PyObject *self, PyObject *args)
  439. {
  440. return PyObject_CallMethodNoArgs(self, &_Py_ID(close));
  441. }
  442. /* Lower-level APIs */
  443. /* XXX Should these be present even if unimplemented? */
  444. /*[clinic input]
  445. _io._IOBase.fileno
  446. cls: defining_class
  447. /
  448. Return underlying file descriptor if one exists.
  449. Raise OSError if the IO object does not use a file descriptor.
  450. [clinic start generated code]*/
  451. static PyObject *
  452. _io__IOBase_fileno_impl(PyObject *self, PyTypeObject *cls)
  453. /*[clinic end generated code: output=7caaa32a6f4ada3d input=1927c8bea5c85099]*/
  454. {
  455. _PyIO_State *state = get_io_state_by_cls(cls);
  456. return iobase_unsupported(state, "fileno");
  457. }
  458. /*[clinic input]
  459. _io._IOBase.isatty
  460. Return whether this is an 'interactive' stream.
  461. Return False if it can't be determined.
  462. [clinic start generated code]*/
  463. static PyObject *
  464. _io__IOBase_isatty_impl(PyObject *self)
  465. /*[clinic end generated code: output=60cab77cede41cdd input=9ef76530d368458b]*/
  466. {
  467. if (iobase_check_closed(self))
  468. return NULL;
  469. Py_RETURN_FALSE;
  470. }
  471. /* Readline(s) and writelines */
  472. /*[clinic input]
  473. _io._IOBase.readline
  474. size as limit: Py_ssize_t(accept={int, NoneType}) = -1
  475. /
  476. Read and return a line from the stream.
  477. If size is specified, at most size bytes will be read.
  478. The line terminator is always b'\n' for binary files; for text
  479. files, the newlines argument to open can be used to select the line
  480. terminator(s) recognized.
  481. [clinic start generated code]*/
  482. static PyObject *
  483. _io__IOBase_readline_impl(PyObject *self, Py_ssize_t limit)
  484. /*[clinic end generated code: output=4479f79b58187840 input=d0c596794e877bff]*/
  485. {
  486. /* For backwards compatibility, a (slowish) readline(). */
  487. PyObject *peek, *buffer, *result;
  488. Py_ssize_t old_size = -1;
  489. if (_PyObject_LookupAttr(self, &_Py_ID(peek), &peek) < 0) {
  490. return NULL;
  491. }
  492. buffer = PyByteArray_FromStringAndSize(NULL, 0);
  493. if (buffer == NULL) {
  494. Py_XDECREF(peek);
  495. return NULL;
  496. }
  497. while (limit < 0 || PyByteArray_GET_SIZE(buffer) < limit) {
  498. Py_ssize_t nreadahead = 1;
  499. PyObject *b;
  500. if (peek != NULL) {
  501. PyObject *readahead = PyObject_CallOneArg(peek, _PyLong_GetOne());
  502. if (readahead == NULL) {
  503. /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
  504. when EINTR occurs so we needn't do it ourselves. */
  505. if (_PyIO_trap_eintr()) {
  506. continue;
  507. }
  508. goto fail;
  509. }
  510. if (!PyBytes_Check(readahead)) {
  511. PyErr_Format(PyExc_OSError,
  512. "peek() should have returned a bytes object, "
  513. "not '%.200s'", Py_TYPE(readahead)->tp_name);
  514. Py_DECREF(readahead);
  515. goto fail;
  516. }
  517. if (PyBytes_GET_SIZE(readahead) > 0) {
  518. Py_ssize_t n = 0;
  519. const char *buf = PyBytes_AS_STRING(readahead);
  520. if (limit >= 0) {
  521. do {
  522. if (n >= PyBytes_GET_SIZE(readahead) || n >= limit)
  523. break;
  524. if (buf[n++] == '\n')
  525. break;
  526. } while (1);
  527. }
  528. else {
  529. do {
  530. if (n >= PyBytes_GET_SIZE(readahead))
  531. break;
  532. if (buf[n++] == '\n')
  533. break;
  534. } while (1);
  535. }
  536. nreadahead = n;
  537. }
  538. Py_DECREF(readahead);
  539. }
  540. b = _PyObject_CallMethod(self, &_Py_ID(read), "n", nreadahead);
  541. if (b == NULL) {
  542. /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
  543. when EINTR occurs so we needn't do it ourselves. */
  544. if (_PyIO_trap_eintr()) {
  545. continue;
  546. }
  547. goto fail;
  548. }
  549. if (!PyBytes_Check(b)) {
  550. PyErr_Format(PyExc_OSError,
  551. "read() should have returned a bytes object, "
  552. "not '%.200s'", Py_TYPE(b)->tp_name);
  553. Py_DECREF(b);
  554. goto fail;
  555. }
  556. if (PyBytes_GET_SIZE(b) == 0) {
  557. Py_DECREF(b);
  558. break;
  559. }
  560. old_size = PyByteArray_GET_SIZE(buffer);
  561. if (PyByteArray_Resize(buffer, old_size + PyBytes_GET_SIZE(b)) < 0) {
  562. Py_DECREF(b);
  563. goto fail;
  564. }
  565. memcpy(PyByteArray_AS_STRING(buffer) + old_size,
  566. PyBytes_AS_STRING(b), PyBytes_GET_SIZE(b));
  567. Py_DECREF(b);
  568. if (PyByteArray_AS_STRING(buffer)[PyByteArray_GET_SIZE(buffer) - 1] == '\n')
  569. break;
  570. }
  571. result = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(buffer),
  572. PyByteArray_GET_SIZE(buffer));
  573. Py_XDECREF(peek);
  574. Py_DECREF(buffer);
  575. return result;
  576. fail:
  577. Py_XDECREF(peek);
  578. Py_DECREF(buffer);
  579. return NULL;
  580. }
  581. static PyObject *
  582. iobase_iter(PyObject *self)
  583. {
  584. if (iobase_check_closed(self))
  585. return NULL;
  586. return Py_NewRef(self);
  587. }
  588. static PyObject *
  589. iobase_iternext(PyObject *self)
  590. {
  591. PyObject *line = PyObject_CallMethodNoArgs(self, &_Py_ID(readline));
  592. if (line == NULL)
  593. return NULL;
  594. if (PyObject_Size(line) <= 0) {
  595. /* Error or empty */
  596. Py_DECREF(line);
  597. return NULL;
  598. }
  599. return line;
  600. }
  601. /*[clinic input]
  602. _io._IOBase.readlines
  603. hint: Py_ssize_t(accept={int, NoneType}) = -1
  604. /
  605. Return a list of lines from the stream.
  606. hint can be specified to control the number of lines read: no more
  607. lines will be read if the total size (in bytes/characters) of all
  608. lines so far exceeds hint.
  609. [clinic start generated code]*/
  610. static PyObject *
  611. _io__IOBase_readlines_impl(PyObject *self, Py_ssize_t hint)
  612. /*[clinic end generated code: output=2f50421677fa3dea input=9400c786ea9dc416]*/
  613. {
  614. Py_ssize_t length = 0;
  615. PyObject *result, *it = NULL;
  616. result = PyList_New(0);
  617. if (result == NULL)
  618. return NULL;
  619. if (hint <= 0) {
  620. /* XXX special-casing this made sense in the Python version in order
  621. to remove the bytecode interpretation overhead, but it could
  622. probably be removed here. */
  623. PyObject *ret = PyObject_CallMethodObjArgs(result, &_Py_ID(extend),
  624. self, NULL);
  625. if (ret == NULL) {
  626. goto error;
  627. }
  628. Py_DECREF(ret);
  629. return result;
  630. }
  631. it = PyObject_GetIter(self);
  632. if (it == NULL) {
  633. goto error;
  634. }
  635. while (1) {
  636. Py_ssize_t line_length;
  637. PyObject *line = PyIter_Next(it);
  638. if (line == NULL) {
  639. if (PyErr_Occurred()) {
  640. goto error;
  641. }
  642. else
  643. break; /* StopIteration raised */
  644. }
  645. if (PyList_Append(result, line) < 0) {
  646. Py_DECREF(line);
  647. goto error;
  648. }
  649. line_length = PyObject_Size(line);
  650. Py_DECREF(line);
  651. if (line_length < 0) {
  652. goto error;
  653. }
  654. if (line_length > hint - length)
  655. break;
  656. length += line_length;
  657. }
  658. Py_DECREF(it);
  659. return result;
  660. error:
  661. Py_XDECREF(it);
  662. Py_DECREF(result);
  663. return NULL;
  664. }
  665. /*[clinic input]
  666. _io._IOBase.writelines
  667. lines: object
  668. /
  669. Write a list of lines to stream.
  670. Line separators are not added, so it is usual for each of the
  671. lines provided to have a line separator at the end.
  672. [clinic start generated code]*/
  673. static PyObject *
  674. _io__IOBase_writelines(PyObject *self, PyObject *lines)
  675. /*[clinic end generated code: output=976eb0a9b60a6628 input=cac3fc8864183359]*/
  676. {
  677. PyObject *iter, *res;
  678. if (iobase_check_closed(self))
  679. return NULL;
  680. iter = PyObject_GetIter(lines);
  681. if (iter == NULL)
  682. return NULL;
  683. while (1) {
  684. PyObject *line = PyIter_Next(iter);
  685. if (line == NULL) {
  686. if (PyErr_Occurred()) {
  687. Py_DECREF(iter);
  688. return NULL;
  689. }
  690. else
  691. break; /* Stop Iteration */
  692. }
  693. res = NULL;
  694. do {
  695. res = PyObject_CallMethodObjArgs(self, &_Py_ID(write), line, NULL);
  696. } while (res == NULL && _PyIO_trap_eintr());
  697. Py_DECREF(line);
  698. if (res == NULL) {
  699. Py_DECREF(iter);
  700. return NULL;
  701. }
  702. Py_DECREF(res);
  703. }
  704. Py_DECREF(iter);
  705. Py_RETURN_NONE;
  706. }
  707. #define clinic_state() (find_io_state_by_def(Py_TYPE(self)))
  708. #include "clinic/iobase.c.h"
  709. #undef clinic_state
  710. static PyMethodDef iobase_methods[] = {
  711. _IO__IOBASE_SEEK_METHODDEF
  712. _IO__IOBASE_TELL_METHODDEF
  713. _IO__IOBASE_TRUNCATE_METHODDEF
  714. _IO__IOBASE_FLUSH_METHODDEF
  715. _IO__IOBASE_CLOSE_METHODDEF
  716. _IO__IOBASE_SEEKABLE_METHODDEF
  717. _IO__IOBASE_READABLE_METHODDEF
  718. _IO__IOBASE_WRITABLE_METHODDEF
  719. {"_checkClosed", _PyIOBase_check_closed, METH_NOARGS},
  720. {"_checkSeekable", iobase_check_seekable, METH_NOARGS},
  721. {"_checkReadable", iobase_check_readable, METH_NOARGS},
  722. {"_checkWritable", iobase_check_writable, METH_NOARGS},
  723. _IO__IOBASE_FILENO_METHODDEF
  724. _IO__IOBASE_ISATTY_METHODDEF
  725. {"__enter__", iobase_enter, METH_NOARGS},
  726. {"__exit__", iobase_exit, METH_VARARGS},
  727. _IO__IOBASE_READLINE_METHODDEF
  728. _IO__IOBASE_READLINES_METHODDEF
  729. _IO__IOBASE_WRITELINES_METHODDEF
  730. {NULL, NULL}
  731. };
  732. static PyGetSetDef iobase_getset[] = {
  733. {"__dict__", PyObject_GenericGetDict, NULL, NULL},
  734. {"closed", (getter)iobase_closed_get, NULL, NULL},
  735. {NULL}
  736. };
  737. static struct PyMemberDef iobase_members[] = {
  738. {"__weaklistoffset__", T_PYSSIZET, offsetof(iobase, weakreflist), READONLY},
  739. {"__dictoffset__", T_PYSSIZET, offsetof(iobase, dict), READONLY},
  740. {NULL},
  741. };
  742. static PyType_Slot iobase_slots[] = {
  743. {Py_tp_dealloc, iobase_dealloc},
  744. {Py_tp_doc, (void *)iobase_doc},
  745. {Py_tp_traverse, iobase_traverse},
  746. {Py_tp_clear, iobase_clear},
  747. {Py_tp_iter, iobase_iter},
  748. {Py_tp_iternext, iobase_iternext},
  749. {Py_tp_methods, iobase_methods},
  750. {Py_tp_members, iobase_members},
  751. {Py_tp_getset, iobase_getset},
  752. {Py_tp_finalize, iobase_finalize},
  753. {0, NULL},
  754. };
  755. PyType_Spec iobase_spec = {
  756. .name = "_io._IOBase",
  757. .basicsize = sizeof(iobase),
  758. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
  759. Py_TPFLAGS_IMMUTABLETYPE),
  760. .slots = iobase_slots,
  761. };
  762. /*
  763. * RawIOBase class, Inherits from IOBase.
  764. */
  765. PyDoc_STRVAR(rawiobase_doc,
  766. "Base class for raw binary I/O.");
  767. /*
  768. * The read() method is implemented by calling readinto(); derived classes
  769. * that want to support read() only need to implement readinto() as a
  770. * primitive operation. In general, readinto() can be more efficient than
  771. * read().
  772. *
  773. * (It would be tempting to also provide an implementation of readinto() in
  774. * terms of read(), in case the latter is a more suitable primitive operation,
  775. * but that would lead to nasty recursion in case a subclass doesn't implement
  776. * either.)
  777. */
  778. /*[clinic input]
  779. _io._RawIOBase.read
  780. size as n: Py_ssize_t = -1
  781. /
  782. [clinic start generated code]*/
  783. static PyObject *
  784. _io__RawIOBase_read_impl(PyObject *self, Py_ssize_t n)
  785. /*[clinic end generated code: output=6cdeb731e3c9f13c input=b6d0dcf6417d1374]*/
  786. {
  787. PyObject *b, *res;
  788. if (n < 0) {
  789. return PyObject_CallMethodNoArgs(self, &_Py_ID(readall));
  790. }
  791. /* TODO: allocate a bytes object directly instead and manually construct
  792. a writable memoryview pointing to it. */
  793. b = PyByteArray_FromStringAndSize(NULL, n);
  794. if (b == NULL)
  795. return NULL;
  796. res = PyObject_CallMethodObjArgs(self, &_Py_ID(readinto), b, NULL);
  797. if (res == NULL || res == Py_None) {
  798. Py_DECREF(b);
  799. return res;
  800. }
  801. n = PyNumber_AsSsize_t(res, PyExc_ValueError);
  802. Py_DECREF(res);
  803. if (n == -1 && PyErr_Occurred()) {
  804. Py_DECREF(b);
  805. return NULL;
  806. }
  807. res = PyBytes_FromStringAndSize(PyByteArray_AsString(b), n);
  808. Py_DECREF(b);
  809. return res;
  810. }
  811. /*[clinic input]
  812. _io._RawIOBase.readall
  813. Read until EOF, using multiple read() call.
  814. [clinic start generated code]*/
  815. static PyObject *
  816. _io__RawIOBase_readall_impl(PyObject *self)
  817. /*[clinic end generated code: output=1987b9ce929425a0 input=688874141213622a]*/
  818. {
  819. int r;
  820. PyObject *chunks = PyList_New(0);
  821. PyObject *result;
  822. if (chunks == NULL)
  823. return NULL;
  824. while (1) {
  825. PyObject *data = _PyObject_CallMethod(self, &_Py_ID(read),
  826. "i", DEFAULT_BUFFER_SIZE);
  827. if (!data) {
  828. /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
  829. when EINTR occurs so we needn't do it ourselves. */
  830. if (_PyIO_trap_eintr()) {
  831. continue;
  832. }
  833. Py_DECREF(chunks);
  834. return NULL;
  835. }
  836. if (data == Py_None) {
  837. if (PyList_GET_SIZE(chunks) == 0) {
  838. Py_DECREF(chunks);
  839. return data;
  840. }
  841. Py_DECREF(data);
  842. break;
  843. }
  844. if (!PyBytes_Check(data)) {
  845. Py_DECREF(chunks);
  846. Py_DECREF(data);
  847. PyErr_SetString(PyExc_TypeError, "read() should return bytes");
  848. return NULL;
  849. }
  850. if (PyBytes_GET_SIZE(data) == 0) {
  851. /* EOF */
  852. Py_DECREF(data);
  853. break;
  854. }
  855. r = PyList_Append(chunks, data);
  856. Py_DECREF(data);
  857. if (r < 0) {
  858. Py_DECREF(chunks);
  859. return NULL;
  860. }
  861. }
  862. result = _PyBytes_Join((PyObject *)&_Py_SINGLETON(bytes_empty), chunks);
  863. Py_DECREF(chunks);
  864. return result;
  865. }
  866. static PyObject *
  867. rawiobase_readinto(PyObject *self, PyObject *args)
  868. {
  869. PyErr_SetNone(PyExc_NotImplementedError);
  870. return NULL;
  871. }
  872. static PyObject *
  873. rawiobase_write(PyObject *self, PyObject *args)
  874. {
  875. PyErr_SetNone(PyExc_NotImplementedError);
  876. return NULL;
  877. }
  878. static PyMethodDef rawiobase_methods[] = {
  879. _IO__RAWIOBASE_READ_METHODDEF
  880. _IO__RAWIOBASE_READALL_METHODDEF
  881. {"readinto", rawiobase_readinto, METH_VARARGS},
  882. {"write", rawiobase_write, METH_VARARGS},
  883. {NULL, NULL}
  884. };
  885. static PyType_Slot rawiobase_slots[] = {
  886. {Py_tp_doc, (void *)rawiobase_doc},
  887. {Py_tp_methods, rawiobase_methods},
  888. {0, NULL},
  889. };
  890. /* Do not set Py_TPFLAGS_HAVE_GC so that tp_traverse and tp_clear are inherited */
  891. PyType_Spec rawiobase_spec = {
  892. .name = "_io._RawIOBase",
  893. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
  894. Py_TPFLAGS_IMMUTABLETYPE),
  895. .slots = rawiobase_slots,
  896. };