modio.c 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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 <assert.h>
  27. #include <string.h>
  28. #include "py/runtime.h"
  29. #include "py/builtin.h"
  30. #include "py/stream.h"
  31. #include "py/binary.h"
  32. #include "py/objarray.h"
  33. #include "py/objstringio.h"
  34. #include "py/frozenmod.h"
  35. #if MICROPY_PY_IO
  36. extern const mp_obj_type_t mp_type_fileio;
  37. extern const mp_obj_type_t mp_type_textio;
  38. #if MICROPY_PY_IO_IOBASE
  39. STATIC const mp_obj_type_t mp_type_iobase;
  40. STATIC const mp_obj_base_t iobase_singleton = {&mp_type_iobase};
  41. STATIC mp_obj_t iobase_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  42. (void)type;
  43. (void)n_args;
  44. (void)n_kw;
  45. (void)args;
  46. return MP_OBJ_FROM_PTR(&iobase_singleton);
  47. }
  48. STATIC mp_uint_t iobase_read_write(mp_obj_t obj, void *buf, mp_uint_t size, int *errcode, qstr qst) {
  49. mp_obj_t dest[3];
  50. mp_load_method(obj, qst, dest);
  51. mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, size, buf};
  52. dest[2] = MP_OBJ_FROM_PTR(&ar);
  53. mp_obj_t ret_obj = mp_call_method_n_kw(1, 0, dest);
  54. if (ret_obj == mp_const_none) {
  55. *errcode = MP_EAGAIN;
  56. return MP_STREAM_ERROR;
  57. }
  58. mp_int_t ret = mp_obj_get_int(ret_obj);
  59. if (ret >= 0) {
  60. return ret;
  61. } else {
  62. *errcode = -ret;
  63. return MP_STREAM_ERROR;
  64. }
  65. }
  66. STATIC mp_uint_t iobase_read(mp_obj_t obj, void *buf, mp_uint_t size, int *errcode) {
  67. return iobase_read_write(obj, buf, size, errcode, MP_QSTR_readinto);
  68. }
  69. STATIC mp_uint_t iobase_write(mp_obj_t obj, const void *buf, mp_uint_t size, int *errcode) {
  70. return iobase_read_write(obj, (void *)buf, size, errcode, MP_QSTR_write);
  71. }
  72. STATIC mp_uint_t iobase_ioctl(mp_obj_t obj, mp_uint_t request, uintptr_t arg, int *errcode) {
  73. mp_obj_t dest[4];
  74. mp_load_method(obj, MP_QSTR_ioctl, dest);
  75. dest[2] = mp_obj_new_int_from_uint(request);
  76. dest[3] = mp_obj_new_int_from_uint(arg);
  77. mp_int_t ret = mp_obj_get_int(mp_call_method_n_kw(2, 0, dest));
  78. if (ret >= 0) {
  79. return ret;
  80. } else {
  81. *errcode = -ret;
  82. return MP_STREAM_ERROR;
  83. }
  84. }
  85. STATIC const mp_stream_p_t iobase_p = {
  86. .read = iobase_read,
  87. .write = iobase_write,
  88. .ioctl = iobase_ioctl,
  89. };
  90. STATIC const mp_obj_type_t mp_type_iobase = {
  91. { &mp_type_type },
  92. .name = MP_QSTR_IOBase,
  93. .make_new = iobase_make_new,
  94. .protocol = &iobase_p,
  95. };
  96. #endif // MICROPY_PY_IO_IOBASE
  97. #if MICROPY_PY_IO_BUFFEREDWRITER
  98. typedef struct _mp_obj_bufwriter_t {
  99. mp_obj_base_t base;
  100. mp_obj_t stream;
  101. size_t alloc;
  102. size_t len;
  103. byte buf[0];
  104. } mp_obj_bufwriter_t;
  105. STATIC mp_obj_t bufwriter_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  106. mp_arg_check_num(n_args, n_kw, 2, 2, false);
  107. size_t alloc = mp_obj_get_int(args[1]);
  108. mp_obj_bufwriter_t *o = m_new_obj_var(mp_obj_bufwriter_t, byte, alloc);
  109. o->base.type = type;
  110. o->stream = args[0];
  111. o->alloc = alloc;
  112. o->len = 0;
  113. return o;
  114. }
  115. STATIC mp_uint_t bufwriter_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) {
  116. mp_obj_bufwriter_t *self = MP_OBJ_TO_PTR(self_in);
  117. mp_uint_t org_size = size;
  118. while (size > 0) {
  119. mp_uint_t rem = self->alloc - self->len;
  120. if (size < rem) {
  121. memcpy(self->buf + self->len, buf, size);
  122. self->len += size;
  123. return org_size;
  124. }
  125. // Buffer flushing policy here is to flush entire buffer all the time.
  126. // This allows e.g. to have a block device as backing storage and write
  127. // entire block to it. memcpy below is not ideal and could be optimized
  128. // in some cases. But the way it is now it at least ensures that buffer
  129. // is word-aligned, to guard against obscure cases when it matters, e.g.
  130. // https://github.com/micropython/micropython/issues/1863
  131. memcpy(self->buf + self->len, buf, rem);
  132. buf = (byte *)buf + rem;
  133. size -= rem;
  134. mp_uint_t out_sz = mp_stream_write_exactly(self->stream, self->buf, self->alloc, errcode);
  135. (void)out_sz;
  136. if (*errcode != 0) {
  137. return MP_STREAM_ERROR;
  138. }
  139. // TODO: try to recover from a case of non-blocking stream, e.g. move
  140. // remaining chunk to the beginning of buffer.
  141. assert(out_sz == self->alloc);
  142. self->len = 0;
  143. }
  144. return org_size;
  145. }
  146. STATIC mp_obj_t bufwriter_flush(mp_obj_t self_in) {
  147. mp_obj_bufwriter_t *self = MP_OBJ_TO_PTR(self_in);
  148. if (self->len != 0) {
  149. int err;
  150. mp_uint_t out_sz = mp_stream_write_exactly(self->stream, self->buf, self->len, &err);
  151. (void)out_sz;
  152. // TODO: try to recover from a case of non-blocking stream, e.g. move
  153. // remaining chunk to the beginning of buffer.
  154. assert(out_sz == self->len);
  155. self->len = 0;
  156. if (err != 0) {
  157. mp_raise_OSError(err);
  158. }
  159. }
  160. return mp_const_none;
  161. }
  162. STATIC MP_DEFINE_CONST_FUN_OBJ_1(bufwriter_flush_obj, bufwriter_flush);
  163. STATIC const mp_rom_map_elem_t bufwriter_locals_dict_table[] = {
  164. { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
  165. { MP_ROM_QSTR(MP_QSTR_flush), MP_ROM_PTR(&bufwriter_flush_obj) },
  166. };
  167. STATIC MP_DEFINE_CONST_DICT(bufwriter_locals_dict, bufwriter_locals_dict_table);
  168. STATIC const mp_stream_p_t bufwriter_stream_p = {
  169. .write = bufwriter_write,
  170. };
  171. STATIC const mp_obj_type_t bufwriter_type = {
  172. { &mp_type_type },
  173. .name = MP_QSTR_BufferedWriter,
  174. .make_new = bufwriter_make_new,
  175. .protocol = &bufwriter_stream_p,
  176. .locals_dict = (mp_obj_dict_t *)&bufwriter_locals_dict,
  177. };
  178. #endif // MICROPY_PY_IO_BUFFEREDWRITER
  179. #if MICROPY_PY_IO_RESOURCE_STREAM
  180. STATIC mp_obj_t resource_stream(mp_obj_t package_in, mp_obj_t path_in) {
  181. VSTR_FIXED(path_buf, MICROPY_ALLOC_PATH_MAX);
  182. size_t len;
  183. // As an extension to pkg_resources.resource_stream(), we support
  184. // package parameter being None, the path_in is interpreted as a
  185. // raw path.
  186. if (package_in != mp_const_none) {
  187. // Pass "True" as sentinel value in fromlist to force returning of leaf module
  188. mp_obj_t pkg = mp_import_name(mp_obj_str_get_qstr(package_in), mp_const_true, MP_OBJ_NEW_SMALL_INT(0));
  189. mp_obj_t dest[2];
  190. mp_load_method_maybe(pkg, MP_QSTR___path__, dest);
  191. if (dest[0] == MP_OBJ_NULL) {
  192. mp_raise_TypeError(NULL);
  193. }
  194. const char *path = mp_obj_str_get_data(dest[0], &len);
  195. vstr_add_strn(&path_buf, path, len);
  196. vstr_add_byte(&path_buf, '/');
  197. }
  198. const char *path = mp_obj_str_get_data(path_in, &len);
  199. vstr_add_strn(&path_buf, path, len);
  200. len = path_buf.len;
  201. const char *data = mp_find_frozen_str(path_buf.buf, &len);
  202. if (data != NULL) {
  203. mp_obj_stringio_t *o = m_new_obj(mp_obj_stringio_t);
  204. o->base.type = &mp_type_bytesio;
  205. o->vstr = m_new_obj(vstr_t);
  206. vstr_init_fixed_buf(o->vstr, len + 1, (char *)data);
  207. o->vstr->len = len;
  208. o->pos = 0;
  209. return MP_OBJ_FROM_PTR(o);
  210. }
  211. mp_obj_t path_out = mp_obj_new_str(path_buf.buf, path_buf.len);
  212. return mp_builtin_open(1, &path_out, (mp_map_t *)&mp_const_empty_map);
  213. }
  214. STATIC MP_DEFINE_CONST_FUN_OBJ_2(resource_stream_obj, resource_stream);
  215. #endif
  216. STATIC const mp_rom_map_elem_t mp_module_io_globals_table[] = {
  217. { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_uio) },
  218. // Note: mp_builtin_open_obj should be defined by port, it's not
  219. // part of the core.
  220. { MP_ROM_QSTR(MP_QSTR_open), MP_ROM_PTR(&mp_builtin_open_obj) },
  221. #if MICROPY_PY_IO_IOBASE
  222. { MP_ROM_QSTR(MP_QSTR_IOBase), MP_ROM_PTR(&mp_type_iobase) },
  223. #endif
  224. #if MICROPY_PY_IO_RESOURCE_STREAM
  225. { MP_ROM_QSTR(MP_QSTR_resource_stream), MP_ROM_PTR(&resource_stream_obj) },
  226. #endif
  227. #if MICROPY_PY_IO_FILEIO
  228. { MP_ROM_QSTR(MP_QSTR_FileIO), MP_ROM_PTR(&mp_type_fileio) },
  229. #if MICROPY_CPYTHON_COMPAT
  230. { MP_ROM_QSTR(MP_QSTR_TextIOWrapper), MP_ROM_PTR(&mp_type_textio) },
  231. #endif
  232. #endif
  233. { MP_ROM_QSTR(MP_QSTR_StringIO), MP_ROM_PTR(&mp_type_stringio) },
  234. #if MICROPY_PY_IO_BYTESIO
  235. { MP_ROM_QSTR(MP_QSTR_BytesIO), MP_ROM_PTR(&mp_type_bytesio) },
  236. #endif
  237. #if MICROPY_PY_IO_BUFFEREDWRITER
  238. { MP_ROM_QSTR(MP_QSTR_BufferedWriter), MP_ROM_PTR(&bufwriter_type) },
  239. #endif
  240. };
  241. STATIC MP_DEFINE_CONST_DICT(mp_module_io_globals, mp_module_io_globals_table);
  242. const mp_obj_module_t mp_module_io = {
  243. .base = { &mp_type_module },
  244. .globals = (mp_obj_dict_t *)&mp_module_io_globals,
  245. };
  246. #endif