qstr.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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 <stdio.h>
  29. #include "py/mpstate.h"
  30. #include "py/qstr.h"
  31. #include "py/gc.h"
  32. #include "py/runtime.h"
  33. // NOTE: we are using linear arrays to store and search for qstr's (unique strings, interned strings)
  34. // ultimately we will replace this with a static hash table of some kind
  35. // also probably need to include the length in the string data, to allow null bytes in the string
  36. #if MICROPY_DEBUG_VERBOSE // print debugging info
  37. #define DEBUG_printf DEBUG_printf
  38. #else // don't print debugging info
  39. #define DEBUG_printf(...) (void)0
  40. #endif
  41. // A qstr is an index into the qstr pool.
  42. // The data for a qstr contains (hash, length, data):
  43. // - hash (configurable number of bytes)
  44. // - length (configurable number of bytes)
  45. // - data ("length" number of bytes)
  46. // - \0 terminated (so they can be printed using printf)
  47. #if MICROPY_QSTR_BYTES_IN_HASH == 1
  48. #define Q_HASH_MASK (0xff)
  49. #define Q_GET_HASH(q) ((mp_uint_t)(q)[0])
  50. #define Q_SET_HASH(q, hash) do { (q)[0] = (hash); } while (0)
  51. #elif MICROPY_QSTR_BYTES_IN_HASH == 2
  52. #define Q_HASH_MASK (0xffff)
  53. #define Q_GET_HASH(q) ((mp_uint_t)(q)[0] | ((mp_uint_t)(q)[1] << 8))
  54. #define Q_SET_HASH(q, hash) do { (q)[0] = (hash); (q)[1] = (hash) >> 8; } while (0)
  55. #else
  56. #error unimplemented qstr hash decoding
  57. #endif
  58. #define Q_GET_ALLOC(q) (MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN + Q_GET_LENGTH(q) + 1)
  59. #define Q_GET_DATA(q) ((q) + MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN)
  60. #if MICROPY_QSTR_BYTES_IN_LEN == 1
  61. #define Q_GET_LENGTH(q) ((q)[MICROPY_QSTR_BYTES_IN_HASH])
  62. #define Q_SET_LENGTH(q, len) do { (q)[MICROPY_QSTR_BYTES_IN_HASH] = (len); } while (0)
  63. #elif MICROPY_QSTR_BYTES_IN_LEN == 2
  64. #define Q_GET_LENGTH(q) ((q)[MICROPY_QSTR_BYTES_IN_HASH] | ((q)[MICROPY_QSTR_BYTES_IN_HASH + 1] << 8))
  65. #define Q_SET_LENGTH(q, len) do { (q)[MICROPY_QSTR_BYTES_IN_HASH] = (len); (q)[MICROPY_QSTR_BYTES_IN_HASH + 1] = (len) >> 8; } while (0)
  66. #else
  67. #error unimplemented qstr length decoding
  68. #endif
  69. #if MICROPY_PY_THREAD && !MICROPY_PY_THREAD_GIL
  70. #define QSTR_ENTER() mp_thread_mutex_lock(&MP_STATE_VM(qstr_mutex), 1)
  71. #define QSTR_EXIT() mp_thread_mutex_unlock(&MP_STATE_VM(qstr_mutex))
  72. #else
  73. #define QSTR_ENTER()
  74. #define QSTR_EXIT()
  75. #endif
  76. // Initial number of entries for qstr pool, set so that the first dynamically
  77. // allocated pool is twice this size. The value here must be <= MP_QSTRnumber_of.
  78. #define MICROPY_ALLOC_QSTR_ENTRIES_INIT (10)
  79. // this must match the equivalent function in makeqstrdata.py
  80. mp_uint_t qstr_compute_hash(const byte *data, size_t len) {
  81. // djb2 algorithm; see http://www.cse.yorku.ca/~oz/hash.html
  82. mp_uint_t hash = 5381;
  83. for (const byte *top = data + len; data < top; data++) {
  84. hash = ((hash << 5) + hash) ^ (*data); // hash * 33 ^ data
  85. }
  86. hash &= Q_HASH_MASK;
  87. // Make sure that valid hash is never zero, zero means "hash not computed"
  88. if (hash == 0) {
  89. hash++;
  90. }
  91. return hash;
  92. }
  93. const qstr_pool_t mp_qstr_const_pool = {
  94. NULL, // no previous pool
  95. 0, // no previous pool
  96. MICROPY_ALLOC_QSTR_ENTRIES_INIT,
  97. MP_QSTRnumber_of, // corresponds to number of strings in array just below
  98. {
  99. #ifndef NO_QSTR
  100. #define QDEF(id, str) str,
  101. #include "genhdr/qstrdefs.generated.h"
  102. #undef QDEF
  103. #endif
  104. },
  105. };
  106. #ifdef MICROPY_QSTR_EXTRA_POOL
  107. extern const qstr_pool_t MICROPY_QSTR_EXTRA_POOL;
  108. #define CONST_POOL MICROPY_QSTR_EXTRA_POOL
  109. #else
  110. #define CONST_POOL mp_qstr_const_pool
  111. #endif
  112. void qstr_init(void) {
  113. MP_STATE_VM(last_pool) = (qstr_pool_t *)&CONST_POOL; // we won't modify the const_pool since it has no allocated room left
  114. MP_STATE_VM(qstr_last_chunk) = NULL;
  115. #if MICROPY_PY_THREAD && !MICROPY_PY_THREAD_GIL
  116. mp_thread_mutex_init(&MP_STATE_VM(qstr_mutex));
  117. #endif
  118. }
  119. STATIC const byte *find_qstr(qstr q) {
  120. // search pool for this qstr
  121. // total_prev_len==0 in the final pool, so the loop will always terminate
  122. qstr_pool_t *pool = MP_STATE_VM(last_pool);
  123. while (q < pool->total_prev_len) {
  124. pool = pool->prev;
  125. }
  126. return pool->qstrs[q - pool->total_prev_len];
  127. }
  128. // qstr_mutex must be taken while in this function
  129. STATIC qstr qstr_add(const byte *q_ptr) {
  130. DEBUG_printf("QSTR: add hash=%d len=%d data=%.*s\n", Q_GET_HASH(q_ptr), Q_GET_LENGTH(q_ptr), Q_GET_LENGTH(q_ptr), Q_GET_DATA(q_ptr));
  131. // make sure we have room in the pool for a new qstr
  132. if (MP_STATE_VM(last_pool)->len >= MP_STATE_VM(last_pool)->alloc) {
  133. size_t new_alloc = MP_STATE_VM(last_pool)->alloc * 2;
  134. #ifdef MICROPY_QSTR_EXTRA_POOL
  135. // Put a lower bound on the allocation size in case the extra qstr pool has few entries
  136. new_alloc = MAX(MICROPY_ALLOC_QSTR_ENTRIES_INIT, new_alloc);
  137. #endif
  138. qstr_pool_t *pool = m_new_obj_var_maybe(qstr_pool_t, const char *, new_alloc);
  139. if (pool == NULL) {
  140. QSTR_EXIT();
  141. m_malloc_fail(new_alloc);
  142. }
  143. pool->prev = MP_STATE_VM(last_pool);
  144. pool->total_prev_len = MP_STATE_VM(last_pool)->total_prev_len + MP_STATE_VM(last_pool)->len;
  145. pool->alloc = new_alloc;
  146. pool->len = 0;
  147. MP_STATE_VM(last_pool) = pool;
  148. DEBUG_printf("QSTR: allocate new pool of size %d\n", MP_STATE_VM(last_pool)->alloc);
  149. }
  150. // add the new qstr
  151. MP_STATE_VM(last_pool)->qstrs[MP_STATE_VM(last_pool)->len++] = q_ptr;
  152. // return id for the newly-added qstr
  153. return MP_STATE_VM(last_pool)->total_prev_len + MP_STATE_VM(last_pool)->len - 1;
  154. }
  155. qstr qstr_find_strn(const char *str, size_t str_len) {
  156. // work out hash of str
  157. mp_uint_t str_hash = qstr_compute_hash((const byte *)str, str_len);
  158. // search pools for the data
  159. for (qstr_pool_t *pool = MP_STATE_VM(last_pool); pool != NULL; pool = pool->prev) {
  160. for (const byte **q = pool->qstrs, **q_top = pool->qstrs + pool->len; q < q_top; q++) {
  161. if (Q_GET_HASH(*q) == str_hash && Q_GET_LENGTH(*q) == str_len && memcmp(Q_GET_DATA(*q), str, str_len) == 0) {
  162. return pool->total_prev_len + (q - pool->qstrs);
  163. }
  164. }
  165. }
  166. // not found; return null qstr
  167. return 0;
  168. }
  169. qstr qstr_from_str(const char *str) {
  170. return qstr_from_strn(str, strlen(str));
  171. }
  172. qstr qstr_from_strn(const char *str, size_t len) {
  173. QSTR_ENTER();
  174. qstr q = qstr_find_strn(str, len);
  175. if (q == 0) {
  176. // qstr does not exist in interned pool so need to add it
  177. // check that len is not too big
  178. if (len >= (1 << (8 * MICROPY_QSTR_BYTES_IN_LEN))) {
  179. QSTR_EXIT();
  180. mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("name too long"));
  181. }
  182. // compute number of bytes needed to intern this string
  183. size_t n_bytes = MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN + len + 1;
  184. if (MP_STATE_VM(qstr_last_chunk) != NULL && MP_STATE_VM(qstr_last_used) + n_bytes > MP_STATE_VM(qstr_last_alloc)) {
  185. // not enough room at end of previously interned string so try to grow
  186. byte *new_p = m_renew_maybe(byte, MP_STATE_VM(qstr_last_chunk), MP_STATE_VM(qstr_last_alloc), MP_STATE_VM(qstr_last_alloc) + n_bytes, false);
  187. if (new_p == NULL) {
  188. // could not grow existing memory; shrink it to fit previous
  189. (void)m_renew_maybe(byte, MP_STATE_VM(qstr_last_chunk), MP_STATE_VM(qstr_last_alloc), MP_STATE_VM(qstr_last_used), false);
  190. MP_STATE_VM(qstr_last_chunk) = NULL;
  191. } else {
  192. // could grow existing memory
  193. MP_STATE_VM(qstr_last_alloc) += n_bytes;
  194. }
  195. }
  196. if (MP_STATE_VM(qstr_last_chunk) == NULL) {
  197. // no existing memory for the interned string so allocate a new chunk
  198. size_t al = n_bytes;
  199. if (al < MICROPY_ALLOC_QSTR_CHUNK_INIT) {
  200. al = MICROPY_ALLOC_QSTR_CHUNK_INIT;
  201. }
  202. MP_STATE_VM(qstr_last_chunk) = m_new_maybe(byte, al);
  203. if (MP_STATE_VM(qstr_last_chunk) == NULL) {
  204. // failed to allocate a large chunk so try with exact size
  205. MP_STATE_VM(qstr_last_chunk) = m_new_maybe(byte, n_bytes);
  206. if (MP_STATE_VM(qstr_last_chunk) == NULL) {
  207. QSTR_EXIT();
  208. m_malloc_fail(n_bytes);
  209. }
  210. al = n_bytes;
  211. }
  212. MP_STATE_VM(qstr_last_alloc) = al;
  213. MP_STATE_VM(qstr_last_used) = 0;
  214. }
  215. // allocate memory from the chunk for this new interned string's data
  216. byte *q_ptr = MP_STATE_VM(qstr_last_chunk) + MP_STATE_VM(qstr_last_used);
  217. MP_STATE_VM(qstr_last_used) += n_bytes;
  218. // store the interned strings' data
  219. mp_uint_t hash = qstr_compute_hash((const byte *)str, len);
  220. Q_SET_HASH(q_ptr, hash);
  221. Q_SET_LENGTH(q_ptr, len);
  222. memcpy(q_ptr + MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN, str, len);
  223. q_ptr[MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN + len] = '\0';
  224. q = qstr_add(q_ptr);
  225. }
  226. QSTR_EXIT();
  227. return q;
  228. }
  229. mp_uint_t qstr_hash(qstr q) {
  230. const byte *qd = find_qstr(q);
  231. return Q_GET_HASH(qd);
  232. }
  233. size_t qstr_len(qstr q) {
  234. const byte *qd = find_qstr(q);
  235. return Q_GET_LENGTH(qd);
  236. }
  237. const char *qstr_str(qstr q) {
  238. const byte *qd = find_qstr(q);
  239. return (const char *)Q_GET_DATA(qd);
  240. }
  241. const byte *qstr_data(qstr q, size_t *len) {
  242. const byte *qd = find_qstr(q);
  243. *len = Q_GET_LENGTH(qd);
  244. return Q_GET_DATA(qd);
  245. }
  246. void qstr_pool_info(size_t *n_pool, size_t *n_qstr, size_t *n_str_data_bytes, size_t *n_total_bytes) {
  247. QSTR_ENTER();
  248. *n_pool = 0;
  249. *n_qstr = 0;
  250. *n_str_data_bytes = 0;
  251. *n_total_bytes = 0;
  252. for (qstr_pool_t *pool = MP_STATE_VM(last_pool); pool != NULL && pool != &CONST_POOL; pool = pool->prev) {
  253. *n_pool += 1;
  254. *n_qstr += pool->len;
  255. for (const byte **q = pool->qstrs, **q_top = pool->qstrs + pool->len; q < q_top; q++) {
  256. *n_str_data_bytes += Q_GET_ALLOC(*q);
  257. }
  258. #if MICROPY_ENABLE_GC
  259. *n_total_bytes += gc_nbytes(pool); // this counts actual bytes used in heap
  260. #else
  261. *n_total_bytes += sizeof(qstr_pool_t) + sizeof(qstr) * pool->alloc;
  262. #endif
  263. }
  264. *n_total_bytes += *n_str_data_bytes;
  265. QSTR_EXIT();
  266. }
  267. #if MICROPY_PY_MICROPYTHON_MEM_INFO
  268. void qstr_dump_data(void) {
  269. QSTR_ENTER();
  270. for (qstr_pool_t *pool = MP_STATE_VM(last_pool); pool != NULL && pool != &CONST_POOL; pool = pool->prev) {
  271. for (const byte **q = pool->qstrs, **q_top = pool->qstrs + pool->len; q < q_top; q++) {
  272. mp_printf(&mp_plat_print, "Q(%s)\n", Q_GET_DATA(*q));
  273. }
  274. }
  275. QSTR_EXIT();
  276. }
  277. #endif
  278. #if MICROPY_ROM_TEXT_COMPRESSION
  279. #ifdef NO_QSTR
  280. // If NO_QSTR is set, it means we're doing QSTR extraction.
  281. // So we won't yet have "genhdr/compressed.data.h"
  282. #else
  283. // Emit the compressed_string_data string.
  284. #define MP_COMPRESSED_DATA(x) STATIC const char *compressed_string_data = x;
  285. #define MP_MATCH_COMPRESSED(a, b)
  286. #include "genhdr/compressed.data.h"
  287. #undef MP_COMPRESSED_DATA
  288. #undef MP_MATCH_COMPRESSED
  289. #endif // NO_QSTR
  290. // This implements the "common word" compression scheme (see makecompresseddata.py) where the most
  291. // common 128 words in error messages are replaced by their index into the list of common words.
  292. // The compressed string data is delimited by setting high bit in the final char of each word.
  293. // e.g. aaaa<0x80|a>bbbbbb<0x80|b>....
  294. // This method finds the n'th string.
  295. STATIC const byte *find_uncompressed_string(uint8_t n) {
  296. const byte *c = (byte *)compressed_string_data;
  297. while (n > 0) {
  298. while ((*c & 0x80) == 0) {
  299. ++c;
  300. }
  301. ++c;
  302. --n;
  303. }
  304. return c;
  305. }
  306. // Given a compressed string in src, decompresses it into dst.
  307. // dst must be large enough (use MP_MAX_UNCOMPRESSED_TEXT_LEN+1).
  308. void mp_decompress_rom_string(byte *dst, const mp_rom_error_text_t src_chr) {
  309. // Skip past the 0xff marker.
  310. const byte *src = (byte *)src_chr + 1;
  311. // Need to add spaces around compressed words, except for the first (i.e. transition from 1<->2).
  312. // 0 = start, 1 = compressed, 2 = regular.
  313. int state = 0;
  314. while (*src) {
  315. if ((byte) * src >= 128) {
  316. if (state != 0) {
  317. *dst++ = ' ';
  318. }
  319. state = 1;
  320. // High bit set, replace with common word.
  321. const byte *word = find_uncompressed_string(*src & 0x7f);
  322. // The word is terminated by the final char having its high bit set.
  323. while ((*word & 0x80) == 0) {
  324. *dst++ = *word++;
  325. }
  326. *dst++ = (*word & 0x7f);
  327. } else {
  328. // Otherwise just copy one char.
  329. if (state == 1) {
  330. *dst++ = ' ';
  331. }
  332. state = 2;
  333. *dst++ = *src;
  334. }
  335. ++src;
  336. }
  337. // Add null-terminator.
  338. *dst = 0;
  339. }
  340. #endif // MICROPY_ROM_TEXT_COMPRESSION