modfile.c 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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 <stdio.h>
  33. #include <unistd.h>
  34. #include <fcntl.h>
  35. #include <errno.h>
  36. #include <sys/stat.h>
  37. #include <sys/types.h>
  38. #ifdef _WIN32
  39. #define fsync _commit
  40. #endif
  41. typedef struct _mp_obj_fdfile_t {
  42. mp_obj_base_t base;
  43. int fd;
  44. } mp_obj_fdfile_t;
  45. #ifdef MICROPY_CPYTHON_COMPAT
  46. STATIC void check_fd_is_open(const mp_obj_fdfile_t *o) {
  47. if (o->fd < 0) {
  48. mp_raise_ValueError("I/O operation on closed file");
  49. }
  50. }
  51. #else
  52. #define check_fd_is_open(o)
  53. #endif
  54. extern const mp_obj_type_t mp_type_fileio;
  55. extern const mp_obj_type_t mp_type_textio;
  56. STATIC void fdfile_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  57. (void)kind;
  58. mp_obj_fdfile_t *self = MP_OBJ_TO_PTR(self_in);
  59. mp_printf(print, "<io.%s %d>", mp_obj_get_type_str(self_in), self->fd);
  60. }
  61. STATIC mp_uint_t fdfile_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errcode) {
  62. mp_obj_fdfile_t *o = MP_OBJ_TO_PTR(o_in);
  63. check_fd_is_open(o);
  64. mp_int_t r = read(o->fd, buf, size);
  65. if (r == -1) {
  66. *errcode = errno;
  67. return MP_STREAM_ERROR;
  68. }
  69. return r;
  70. }
  71. STATIC mp_uint_t fdfile_write(mp_obj_t o_in, const void *buf, mp_uint_t size, int *errcode) {
  72. mp_obj_fdfile_t *o = MP_OBJ_TO_PTR(o_in);
  73. check_fd_is_open(o);
  74. #if MICROPY_PY_OS_DUPTERM
  75. if (o->fd <= STDERR_FILENO) {
  76. mp_hal_stdout_tx_strn(buf, size);
  77. return size;
  78. }
  79. #endif
  80. mp_int_t r = write(o->fd, buf, size);
  81. while (r == -1 && errno == EINTR) {
  82. if (MP_STATE_VM(mp_pending_exception) != MP_OBJ_NULL) {
  83. mp_obj_t obj = MP_STATE_VM(mp_pending_exception);
  84. MP_STATE_VM(mp_pending_exception) = MP_OBJ_NULL;
  85. nlr_raise(obj);
  86. }
  87. r = write(o->fd, buf, size);
  88. }
  89. if (r == -1) {
  90. *errcode = errno;
  91. return MP_STREAM_ERROR;
  92. }
  93. return r;
  94. }
  95. STATIC mp_uint_t fdfile_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) {
  96. mp_obj_fdfile_t *o = MP_OBJ_TO_PTR(o_in);
  97. check_fd_is_open(o);
  98. switch (request) {
  99. case MP_STREAM_SEEK: {
  100. struct mp_stream_seek_t *s = (struct mp_stream_seek_t*)arg;
  101. off_t off = lseek(o->fd, s->offset, s->whence);
  102. if (off == (off_t)-1) {
  103. *errcode = errno;
  104. return MP_STREAM_ERROR;
  105. }
  106. s->offset = off;
  107. return 0;
  108. }
  109. case MP_STREAM_FLUSH:
  110. if (fsync(o->fd) < 0) {
  111. *errcode = errno;
  112. return MP_STREAM_ERROR;
  113. }
  114. return 0;
  115. default:
  116. *errcode = EINVAL;
  117. return MP_STREAM_ERROR;
  118. }
  119. }
  120. STATIC mp_obj_t fdfile_close(mp_obj_t self_in) {
  121. mp_obj_fdfile_t *self = MP_OBJ_TO_PTR(self_in);
  122. close(self->fd);
  123. #ifdef MICROPY_CPYTHON_COMPAT
  124. self->fd = -1;
  125. #endif
  126. return mp_const_none;
  127. }
  128. STATIC MP_DEFINE_CONST_FUN_OBJ_1(fdfile_close_obj, fdfile_close);
  129. STATIC mp_obj_t fdfile___exit__(size_t n_args, const mp_obj_t *args) {
  130. (void)n_args;
  131. return fdfile_close(args[0]);
  132. }
  133. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(fdfile___exit___obj, 4, 4, fdfile___exit__);
  134. STATIC mp_obj_t fdfile_fileno(mp_obj_t self_in) {
  135. mp_obj_fdfile_t *self = MP_OBJ_TO_PTR(self_in);
  136. check_fd_is_open(self);
  137. return MP_OBJ_NEW_SMALL_INT(self->fd);
  138. }
  139. STATIC MP_DEFINE_CONST_FUN_OBJ_1(fdfile_fileno_obj, fdfile_fileno);
  140. // Note: encoding is ignored for now; it's also not a valid kwarg for CPython's FileIO,
  141. // but by adding it here we can use one single mp_arg_t array for open() and FileIO's constructor
  142. STATIC const mp_arg_t file_open_args[] = {
  143. { MP_QSTR_file, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} },
  144. { MP_QSTR_mode, MP_ARG_OBJ, {.u_obj = MP_OBJ_NEW_QSTR(MP_QSTR_r)} },
  145. { MP_QSTR_buffering, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} },
  146. { MP_QSTR_encoding, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} },
  147. };
  148. #define FILE_OPEN_NUM_ARGS MP_ARRAY_SIZE(file_open_args)
  149. STATIC mp_obj_t fdfile_open(const mp_obj_type_t *type, mp_arg_val_t *args) {
  150. mp_obj_fdfile_t *o = m_new_obj(mp_obj_fdfile_t);
  151. const char *mode_s = mp_obj_str_get_str(args[1].u_obj);
  152. int mode_rw = 0, mode_x = 0;
  153. while (*mode_s) {
  154. switch (*mode_s++) {
  155. case 'r':
  156. mode_rw = O_RDONLY;
  157. break;
  158. case 'w':
  159. mode_rw = O_WRONLY;
  160. mode_x = O_CREAT | O_TRUNC;
  161. break;
  162. case 'a':
  163. mode_rw = O_WRONLY;
  164. mode_x = O_CREAT | O_APPEND;
  165. break;
  166. case '+':
  167. mode_rw = O_RDWR;
  168. break;
  169. #if MICROPY_PY_IO_FILEIO
  170. // If we don't have io.FileIO, then files are in text mode implicitly
  171. case 'b':
  172. type = &mp_type_fileio;
  173. break;
  174. case 't':
  175. type = &mp_type_textio;
  176. break;
  177. #endif
  178. }
  179. }
  180. o->base.type = type;
  181. mp_obj_t fid = args[0].u_obj;
  182. if (MP_OBJ_IS_SMALL_INT(fid)) {
  183. o->fd = MP_OBJ_SMALL_INT_VALUE(fid);
  184. return MP_OBJ_FROM_PTR(o);
  185. }
  186. const char *fname = mp_obj_str_get_str(fid);
  187. int fd = open(fname, mode_x | mode_rw, 0644);
  188. if (fd == -1) {
  189. mp_raise_OSError(errno);
  190. }
  191. o->fd = fd;
  192. return MP_OBJ_FROM_PTR(o);
  193. }
  194. 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) {
  195. mp_arg_val_t arg_vals[FILE_OPEN_NUM_ARGS];
  196. mp_arg_parse_all_kw_array(n_args, n_kw, args, FILE_OPEN_NUM_ARGS, file_open_args, arg_vals);
  197. return fdfile_open(type, arg_vals);
  198. }
  199. STATIC const mp_rom_map_elem_t rawfile_locals_dict_table[] = {
  200. { MP_ROM_QSTR(MP_QSTR_fileno), MP_ROM_PTR(&fdfile_fileno_obj) },
  201. { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
  202. { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) },
  203. { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) },
  204. { MP_ROM_QSTR(MP_QSTR_readlines), MP_ROM_PTR(&mp_stream_unbuffered_readlines_obj) },
  205. { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
  206. { MP_ROM_QSTR(MP_QSTR_seek), MP_ROM_PTR(&mp_stream_seek_obj) },
  207. { MP_ROM_QSTR(MP_QSTR_tell), MP_ROM_PTR(&mp_stream_tell_obj) },
  208. { MP_ROM_QSTR(MP_QSTR_flush), MP_ROM_PTR(&mp_stream_flush_obj) },
  209. { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&fdfile_close_obj) },
  210. { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&mp_identity_obj) },
  211. { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&fdfile___exit___obj) },
  212. };
  213. STATIC MP_DEFINE_CONST_DICT(rawfile_locals_dict, rawfile_locals_dict_table);
  214. #if MICROPY_PY_IO_FILEIO
  215. STATIC const mp_stream_p_t fileio_stream_p = {
  216. .read = fdfile_read,
  217. .write = fdfile_write,
  218. .ioctl = fdfile_ioctl,
  219. };
  220. const mp_obj_type_t mp_type_fileio = {
  221. { &mp_type_type },
  222. .name = MP_QSTR_FileIO,
  223. .print = fdfile_print,
  224. .make_new = fdfile_make_new,
  225. .getiter = mp_identity_getiter,
  226. .iternext = mp_stream_unbuffered_iter,
  227. .protocol = &fileio_stream_p,
  228. .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict,
  229. };
  230. #endif
  231. STATIC const mp_stream_p_t textio_stream_p = {
  232. .read = fdfile_read,
  233. .write = fdfile_write,
  234. .ioctl = fdfile_ioctl,
  235. .is_text = true,
  236. };
  237. const mp_obj_type_t mp_type_textio = {
  238. { &mp_type_type },
  239. .name = MP_QSTR_TextIOWrapper,
  240. .print = fdfile_print,
  241. .make_new = fdfile_make_new,
  242. .getiter = mp_identity_getiter,
  243. .iternext = mp_stream_unbuffered_iter,
  244. .protocol = &textio_stream_p,
  245. .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict,
  246. };
  247. // Factory function for I/O stream classes
  248. mp_obj_t mp_builtin_open(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
  249. // TODO: analyze buffering args and instantiate appropriate type
  250. mp_arg_val_t arg_vals[FILE_OPEN_NUM_ARGS];
  251. mp_arg_parse_all(n_args, args, kwargs, FILE_OPEN_NUM_ARGS, file_open_args, arg_vals);
  252. return fdfile_open(&mp_type_textio, arg_vals);
  253. }
  254. MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open);
  255. #endif // MICROPY_PY_IO