file.c 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013, 2014 Damien P. George
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #include "py/mpconfig.h"
  27. #if MICROPY_PY_IO
  28. #include "py/runtime.h"
  29. #include "py/stream.h"
  30. #include "py/builtin.h"
  31. #include "py/mphal.h"
  32. #include "fdfile.h"
  33. #include <stdio.h>
  34. #include <unistd.h>
  35. #include <fcntl.h>
  36. #include <errno.h>
  37. #include <sys/stat.h>
  38. #include <sys/types.h>
  39. #ifdef _WIN32
  40. #define fsync _commit
  41. #endif
  42. #ifdef MICROPY_CPYTHON_COMPAT
  43. STATIC void check_fd_is_open(const mp_obj_fdfile_t *o) {
  44. if (o->fd < 0) {
  45. mp_raise_ValueError("I/O operation on closed file");
  46. }
  47. }
  48. #else
  49. #define check_fd_is_open(o)
  50. #endif
  51. extern const mp_obj_type_t mp_type_fileio;
  52. extern const mp_obj_type_t mp_type_textio;
  53. STATIC void fdfile_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  54. (void)kind;
  55. mp_obj_fdfile_t *self = MP_OBJ_TO_PTR(self_in);
  56. mp_printf(print, "<io.%s %d>", mp_obj_get_type_str(self_in), self->fd);
  57. }
  58. STATIC mp_uint_t fdfile_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errcode) {
  59. mp_obj_fdfile_t *o = MP_OBJ_TO_PTR(o_in);
  60. check_fd_is_open(o);
  61. mp_int_t r = read(o->fd, buf, size);
  62. if (r == -1) {
  63. *errcode = errno;
  64. return MP_STREAM_ERROR;
  65. }
  66. return r;
  67. }
  68. STATIC mp_uint_t fdfile_write(mp_obj_t o_in, const void *buf, mp_uint_t size, int *errcode) {
  69. mp_obj_fdfile_t *o = MP_OBJ_TO_PTR(o_in);
  70. check_fd_is_open(o);
  71. #if MICROPY_PY_OS_DUPTERM
  72. if (o->fd <= STDERR_FILENO) {
  73. mp_hal_stdout_tx_strn(buf, size);
  74. return size;
  75. }
  76. #endif
  77. mp_int_t r = write(o->fd, buf, size);
  78. while (r == -1 && errno == EINTR) {
  79. if (MP_STATE_VM(mp_pending_exception) != MP_OBJ_NULL) {
  80. mp_obj_t obj = MP_STATE_VM(mp_pending_exception);
  81. MP_STATE_VM(mp_pending_exception) = MP_OBJ_NULL;
  82. nlr_raise(obj);
  83. }
  84. r = write(o->fd, buf, size);
  85. }
  86. if (r == -1) {
  87. *errcode = errno;
  88. return MP_STREAM_ERROR;
  89. }
  90. return r;
  91. }
  92. STATIC mp_uint_t fdfile_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) {
  93. mp_obj_fdfile_t *o = MP_OBJ_TO_PTR(o_in);
  94. check_fd_is_open(o);
  95. switch (request) {
  96. case MP_STREAM_SEEK: {
  97. struct mp_stream_seek_t *s = (struct mp_stream_seek_t*)arg;
  98. off_t off = lseek(o->fd, s->offset, s->whence);
  99. if (off == (off_t)-1) {
  100. *errcode = errno;
  101. return MP_STREAM_ERROR;
  102. }
  103. s->offset = off;
  104. return 0;
  105. }
  106. case MP_STREAM_FLUSH:
  107. if (fsync(o->fd) < 0) {
  108. *errcode = errno;
  109. return MP_STREAM_ERROR;
  110. }
  111. return 0;
  112. default:
  113. *errcode = EINVAL;
  114. return MP_STREAM_ERROR;
  115. }
  116. }
  117. STATIC mp_obj_t fdfile_close(mp_obj_t self_in) {
  118. mp_obj_fdfile_t *self = MP_OBJ_TO_PTR(self_in);
  119. close(self->fd);
  120. #ifdef MICROPY_CPYTHON_COMPAT
  121. self->fd = -1;
  122. #endif
  123. return mp_const_none;
  124. }
  125. STATIC MP_DEFINE_CONST_FUN_OBJ_1(fdfile_close_obj, fdfile_close);
  126. STATIC mp_obj_t fdfile___exit__(size_t n_args, const mp_obj_t *args) {
  127. (void)n_args;
  128. return fdfile_close(args[0]);
  129. }
  130. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(fdfile___exit___obj, 4, 4, fdfile___exit__);
  131. STATIC mp_obj_t fdfile_fileno(mp_obj_t self_in) {
  132. mp_obj_fdfile_t *self = MP_OBJ_TO_PTR(self_in);
  133. check_fd_is_open(self);
  134. return MP_OBJ_NEW_SMALL_INT(self->fd);
  135. }
  136. STATIC MP_DEFINE_CONST_FUN_OBJ_1(fdfile_fileno_obj, fdfile_fileno);
  137. // Note: encoding is ignored for now; it's also not a valid kwarg for CPython's FileIO,
  138. // but by adding it here we can use one single mp_arg_t array for open() and FileIO's constructor
  139. STATIC const mp_arg_t file_open_args[] = {
  140. { MP_QSTR_file, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} },
  141. { MP_QSTR_mode, MP_ARG_OBJ, {.u_obj = MP_OBJ_NEW_QSTR(MP_QSTR_r)} },
  142. { MP_QSTR_buffering, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} },
  143. { MP_QSTR_encoding, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} },
  144. };
  145. #define FILE_OPEN_NUM_ARGS MP_ARRAY_SIZE(file_open_args)
  146. STATIC mp_obj_t fdfile_open(const mp_obj_type_t *type, mp_arg_val_t *args) {
  147. mp_obj_fdfile_t *o = m_new_obj(mp_obj_fdfile_t);
  148. const char *mode_s = mp_obj_str_get_str(args[1].u_obj);
  149. int mode_rw = 0, mode_x = 0;
  150. while (*mode_s) {
  151. switch (*mode_s++) {
  152. case 'r':
  153. mode_rw = O_RDONLY;
  154. break;
  155. case 'w':
  156. mode_rw = O_WRONLY;
  157. mode_x = O_CREAT | O_TRUNC;
  158. break;
  159. case 'a':
  160. mode_rw = O_WRONLY;
  161. mode_x = O_CREAT | O_APPEND;
  162. break;
  163. case '+':
  164. mode_rw = O_RDWR;
  165. break;
  166. #if MICROPY_PY_IO_FILEIO
  167. // If we don't have io.FileIO, then files are in text mode implicitly
  168. case 'b':
  169. type = &mp_type_fileio;
  170. break;
  171. case 't':
  172. type = &mp_type_textio;
  173. break;
  174. #endif
  175. }
  176. }
  177. o->base.type = type;
  178. mp_obj_t fid = args[0].u_obj;
  179. if (MP_OBJ_IS_SMALL_INT(fid)) {
  180. o->fd = MP_OBJ_SMALL_INT_VALUE(fid);
  181. return MP_OBJ_FROM_PTR(o);
  182. }
  183. const char *fname = mp_obj_str_get_str(fid);
  184. int fd = open(fname, mode_x | mode_rw, 0644);
  185. if (fd == -1) {
  186. mp_raise_OSError(errno);
  187. }
  188. o->fd = fd;
  189. return MP_OBJ_FROM_PTR(o);
  190. }
  191. STATIC mp_obj_t fdfile_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  192. mp_arg_val_t arg_vals[FILE_OPEN_NUM_ARGS];
  193. mp_arg_parse_all_kw_array(n_args, n_kw, args, FILE_OPEN_NUM_ARGS, file_open_args, arg_vals);
  194. return fdfile_open(type, arg_vals);
  195. }
  196. STATIC const mp_rom_map_elem_t rawfile_locals_dict_table[] = {
  197. { MP_ROM_QSTR(MP_QSTR_fileno), MP_ROM_PTR(&fdfile_fileno_obj) },
  198. { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
  199. { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) },
  200. { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) },
  201. { MP_ROM_QSTR(MP_QSTR_readlines), MP_ROM_PTR(&mp_stream_unbuffered_readlines_obj) },
  202. { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
  203. { MP_ROM_QSTR(MP_QSTR_seek), MP_ROM_PTR(&mp_stream_seek_obj) },
  204. { MP_ROM_QSTR(MP_QSTR_tell), MP_ROM_PTR(&mp_stream_tell_obj) },
  205. { MP_ROM_QSTR(MP_QSTR_flush), MP_ROM_PTR(&mp_stream_flush_obj) },
  206. { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&fdfile_close_obj) },
  207. { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&mp_identity_obj) },
  208. { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&fdfile___exit___obj) },
  209. };
  210. STATIC MP_DEFINE_CONST_DICT(rawfile_locals_dict, rawfile_locals_dict_table);
  211. #if MICROPY_PY_IO_FILEIO
  212. STATIC const mp_stream_p_t fileio_stream_p = {
  213. .read = fdfile_read,
  214. .write = fdfile_write,
  215. .ioctl = fdfile_ioctl,
  216. };
  217. const mp_obj_type_t mp_type_fileio = {
  218. { &mp_type_type },
  219. .name = MP_QSTR_FileIO,
  220. .print = fdfile_print,
  221. .make_new = fdfile_make_new,
  222. .getiter = mp_identity_getiter,
  223. .iternext = mp_stream_unbuffered_iter,
  224. .protocol = &fileio_stream_p,
  225. .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict,
  226. };
  227. #endif
  228. STATIC const mp_stream_p_t textio_stream_p = {
  229. .read = fdfile_read,
  230. .write = fdfile_write,
  231. .ioctl = fdfile_ioctl,
  232. .is_text = true,
  233. };
  234. const mp_obj_type_t mp_type_textio = {
  235. { &mp_type_type },
  236. .name = MP_QSTR_TextIOWrapper,
  237. .print = fdfile_print,
  238. .make_new = fdfile_make_new,
  239. .getiter = mp_identity_getiter,
  240. .iternext = mp_stream_unbuffered_iter,
  241. .protocol = &textio_stream_p,
  242. .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict,
  243. };
  244. // Factory function for I/O stream classes
  245. mp_obj_t mp_builtin_open(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
  246. // TODO: analyze buffering args and instantiate appropriate type
  247. mp_arg_val_t arg_vals[FILE_OPEN_NUM_ARGS];
  248. mp_arg_parse_all(n_args, args, kwargs, FILE_OPEN_NUM_ARGS, file_open_args, arg_vals);
  249. return fdfile_open(&mp_type_textio, arg_vals);
  250. }
  251. MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open);
  252. #endif // MICROPY_PY_IO