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