vfs_fat_file.c 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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_VFS && MICROPY_VFS_FAT
  28. #include <stdio.h>
  29. #include "py/runtime.h"
  30. #include "py/stream.h"
  31. #include "py/mperrno.h"
  32. #include "lib/oofatfs/ff.h"
  33. #include "extmod/vfs_fat.h"
  34. // this table converts from FRESULT to POSIX errno
  35. const byte fresult_to_errno_table[20] = {
  36. [FR_OK] = 0,
  37. [FR_DISK_ERR] = MP_EIO,
  38. [FR_INT_ERR] = MP_EIO,
  39. [FR_NOT_READY] = MP_EBUSY,
  40. [FR_NO_FILE] = MP_ENOENT,
  41. [FR_NO_PATH] = MP_ENOENT,
  42. [FR_INVALID_NAME] = MP_EINVAL,
  43. [FR_DENIED] = MP_EACCES,
  44. [FR_EXIST] = MP_EEXIST,
  45. [FR_INVALID_OBJECT] = MP_EINVAL,
  46. [FR_WRITE_PROTECTED] = MP_EROFS,
  47. [FR_INVALID_DRIVE] = MP_ENODEV,
  48. [FR_NOT_ENABLED] = MP_ENODEV,
  49. [FR_NO_FILESYSTEM] = MP_ENODEV,
  50. [FR_MKFS_ABORTED] = MP_EIO,
  51. [FR_TIMEOUT] = MP_EIO,
  52. [FR_LOCKED] = MP_EIO,
  53. [FR_NOT_ENOUGH_CORE] = MP_ENOMEM,
  54. [FR_TOO_MANY_OPEN_FILES] = MP_EMFILE,
  55. [FR_INVALID_PARAMETER] = MP_EINVAL,
  56. };
  57. typedef struct _pyb_file_obj_t {
  58. mp_obj_base_t base;
  59. FIL fp;
  60. } pyb_file_obj_t;
  61. STATIC void file_obj_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  62. (void)kind;
  63. mp_printf(print, "<io.%s %p>", mp_obj_get_type_str(self_in), MP_OBJ_TO_PTR(self_in));
  64. }
  65. STATIC mp_uint_t file_obj_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) {
  66. pyb_file_obj_t *self = MP_OBJ_TO_PTR(self_in);
  67. UINT sz_out;
  68. FRESULT res = f_read(&self->fp, buf, size, &sz_out);
  69. if (res != FR_OK) {
  70. *errcode = fresult_to_errno_table[res];
  71. return MP_STREAM_ERROR;
  72. }
  73. return sz_out;
  74. }
  75. STATIC mp_uint_t file_obj_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) {
  76. pyb_file_obj_t *self = MP_OBJ_TO_PTR(self_in);
  77. UINT sz_out;
  78. FRESULT res = f_write(&self->fp, buf, size, &sz_out);
  79. if (res != FR_OK) {
  80. *errcode = fresult_to_errno_table[res];
  81. return MP_STREAM_ERROR;
  82. }
  83. if (sz_out != size) {
  84. // The FatFS documentation says that this means disk full.
  85. *errcode = MP_ENOSPC;
  86. return MP_STREAM_ERROR;
  87. }
  88. return sz_out;
  89. }
  90. STATIC mp_obj_t file_obj___exit__(size_t n_args, const mp_obj_t *args) {
  91. (void)n_args;
  92. return mp_stream_close(args[0]);
  93. }
  94. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(file_obj___exit___obj, 4, 4, file_obj___exit__);
  95. STATIC mp_uint_t file_obj_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) {
  96. pyb_file_obj_t *self = MP_OBJ_TO_PTR(o_in);
  97. if (request == MP_STREAM_SEEK) {
  98. struct mp_stream_seek_t *s = (struct mp_stream_seek_t*)(uintptr_t)arg;
  99. switch (s->whence) {
  100. case 0: // SEEK_SET
  101. f_lseek(&self->fp, s->offset);
  102. break;
  103. case 1: // SEEK_CUR
  104. f_lseek(&self->fp, f_tell(&self->fp) + s->offset);
  105. break;
  106. case 2: // SEEK_END
  107. f_lseek(&self->fp, f_size(&self->fp) + s->offset);
  108. break;
  109. }
  110. s->offset = f_tell(&self->fp);
  111. return 0;
  112. } else if (request == MP_STREAM_FLUSH) {
  113. FRESULT res = f_sync(&self->fp);
  114. if (res != FR_OK) {
  115. *errcode = fresult_to_errno_table[res];
  116. return MP_STREAM_ERROR;
  117. }
  118. return 0;
  119. } else if (request == MP_STREAM_CLOSE) {
  120. // if fs==NULL then the file is closed and in that case this method is a no-op
  121. if (self->fp.obj.fs != NULL) {
  122. FRESULT res = f_close(&self->fp);
  123. if (res != FR_OK) {
  124. *errcode = fresult_to_errno_table[res];
  125. return MP_STREAM_ERROR;
  126. }
  127. }
  128. return 0;
  129. } else {
  130. *errcode = MP_EINVAL;
  131. return MP_STREAM_ERROR;
  132. }
  133. }
  134. // Note: encoding is ignored for now; it's also not a valid kwarg for CPython's FileIO,
  135. // but by adding it here we can use one single mp_arg_t array for open() and FileIO's constructor
  136. STATIC const mp_arg_t file_open_args[] = {
  137. { MP_QSTR_file, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} },
  138. { MP_QSTR_mode, MP_ARG_OBJ, {.u_obj = MP_OBJ_NEW_QSTR(MP_QSTR_r)} },
  139. { MP_QSTR_encoding, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} },
  140. };
  141. #define FILE_OPEN_NUM_ARGS MP_ARRAY_SIZE(file_open_args)
  142. STATIC mp_obj_t file_open(fs_user_mount_t *vfs, const mp_obj_type_t *type, mp_arg_val_t *args) {
  143. int mode = 0;
  144. const char *mode_s = mp_obj_str_get_str(args[1].u_obj);
  145. // TODO make sure only one of r, w, x, a, and b, t are specified
  146. while (*mode_s) {
  147. switch (*mode_s++) {
  148. case 'r':
  149. mode |= FA_READ;
  150. break;
  151. case 'w':
  152. mode |= FA_WRITE | FA_CREATE_ALWAYS;
  153. break;
  154. case 'x':
  155. mode |= FA_WRITE | FA_CREATE_NEW;
  156. break;
  157. case 'a':
  158. mode |= FA_WRITE | FA_OPEN_ALWAYS;
  159. break;
  160. case '+':
  161. mode |= FA_READ | FA_WRITE;
  162. break;
  163. #if MICROPY_PY_IO_FILEIO
  164. case 'b':
  165. type = &mp_type_vfs_fat_fileio;
  166. break;
  167. #endif
  168. case 't':
  169. type = &mp_type_vfs_fat_textio;
  170. break;
  171. }
  172. }
  173. pyb_file_obj_t *o = m_new_obj_with_finaliser(pyb_file_obj_t);
  174. o->base.type = type;
  175. const char *fname = mp_obj_str_get_str(args[0].u_obj);
  176. assert(vfs != NULL);
  177. FRESULT res = f_open(&vfs->fatfs, &o->fp, fname, mode);
  178. if (res != FR_OK) {
  179. m_del_obj(pyb_file_obj_t, o);
  180. mp_raise_OSError(fresult_to_errno_table[res]);
  181. }
  182. // for 'a' mode, we must begin at the end of the file
  183. if ((mode & FA_OPEN_ALWAYS) != 0) {
  184. f_lseek(&o->fp, f_size(&o->fp));
  185. }
  186. return MP_OBJ_FROM_PTR(o);
  187. }
  188. STATIC mp_obj_t file_obj_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  189. mp_arg_val_t arg_vals[FILE_OPEN_NUM_ARGS];
  190. mp_arg_parse_all_kw_array(n_args, n_kw, args, FILE_OPEN_NUM_ARGS, file_open_args, arg_vals);
  191. return file_open(NULL, type, arg_vals);
  192. }
  193. // TODO gc hook to close the file if not already closed
  194. STATIC const mp_rom_map_elem_t rawfile_locals_dict_table[] = {
  195. { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
  196. { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) },
  197. { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) },
  198. { MP_ROM_QSTR(MP_QSTR_readlines), MP_ROM_PTR(&mp_stream_unbuffered_readlines_obj) },
  199. { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
  200. { MP_ROM_QSTR(MP_QSTR_flush), MP_ROM_PTR(&mp_stream_flush_obj) },
  201. { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) },
  202. { MP_ROM_QSTR(MP_QSTR_seek), MP_ROM_PTR(&mp_stream_seek_obj) },
  203. { MP_ROM_QSTR(MP_QSTR_tell), MP_ROM_PTR(&mp_stream_tell_obj) },
  204. { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_stream_close_obj) },
  205. { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&mp_identity_obj) },
  206. { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&file_obj___exit___obj) },
  207. };
  208. STATIC MP_DEFINE_CONST_DICT(rawfile_locals_dict, rawfile_locals_dict_table);
  209. #if MICROPY_PY_IO_FILEIO
  210. STATIC const mp_stream_p_t fileio_stream_p = {
  211. .read = file_obj_read,
  212. .write = file_obj_write,
  213. .ioctl = file_obj_ioctl,
  214. };
  215. const mp_obj_type_t mp_type_vfs_fat_fileio = {
  216. { &mp_type_type },
  217. .name = MP_QSTR_FileIO,
  218. .print = file_obj_print,
  219. .make_new = file_obj_make_new,
  220. .getiter = mp_identity_getiter,
  221. .iternext = mp_stream_unbuffered_iter,
  222. .protocol = &fileio_stream_p,
  223. .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict,
  224. };
  225. #endif
  226. STATIC const mp_stream_p_t textio_stream_p = {
  227. .read = file_obj_read,
  228. .write = file_obj_write,
  229. .ioctl = file_obj_ioctl,
  230. .is_text = true,
  231. };
  232. const mp_obj_type_t mp_type_vfs_fat_textio = {
  233. { &mp_type_type },
  234. .name = MP_QSTR_TextIOWrapper,
  235. .print = file_obj_print,
  236. .make_new = file_obj_make_new,
  237. .getiter = mp_identity_getiter,
  238. .iternext = mp_stream_unbuffered_iter,
  239. .protocol = &textio_stream_p,
  240. .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict,
  241. };
  242. // Factory function for I/O stream classes
  243. STATIC mp_obj_t fatfs_builtin_open_self(mp_obj_t self_in, mp_obj_t path, mp_obj_t mode) {
  244. // TODO: analyze buffering args and instantiate appropriate type
  245. fs_user_mount_t *self = MP_OBJ_TO_PTR(self_in);
  246. mp_arg_val_t arg_vals[FILE_OPEN_NUM_ARGS];
  247. arg_vals[0].u_obj = path;
  248. arg_vals[1].u_obj = mode;
  249. arg_vals[2].u_obj = mp_const_none;
  250. return file_open(self, &mp_type_vfs_fat_textio, arg_vals);
  251. }
  252. MP_DEFINE_CONST_FUN_OBJ_3(fat_vfs_open_obj, fatfs_builtin_open_self);
  253. #endif // MICROPY_VFS && MICROPY_VFS_FAT