qstr.c 11.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*
 * This file is part of the Micro Python project, http://micropython.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2013, 2014 Damien P. George
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

Damien's avatar
Damien committed
27
28
#include <assert.h>
#include <string.h>
29
#include <stdio.h>
Damien's avatar
Damien committed
30

31
#include "py/mpstate.h"
32
33
#include "py/qstr.h"
#include "py/gc.h"
Damien's avatar
Damien committed
34

35
36
37
38
39
// NOTE: we are using linear arrays to store and search for qstr's (unique strings, interned strings)
// ultimately we will replace this with a static hash table of some kind
// also probably need to include the length in the string data, to allow null bytes in the string

#if 0 // print debugging info
40
#define DEBUG_printf DEBUG_printf
41
#else // don't print debugging info
42
#define DEBUG_printf(...) (void)0
43
44
#endif

45
// A qstr is an index into the qstr pool.
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// The data for a qstr contains (hash, length, data):
//  - hash (configurable number of bytes)
//  - length (configurable number of bytes)
//  - data ("length" number of bytes)
//  - \0 terminated (so they can be printed using printf)

#if MICROPY_QSTR_BYTES_IN_HASH == 1
    #define Q_HASH_MASK (0xff)
    #define Q_GET_HASH(q) ((mp_uint_t)(q)[0])
    #define Q_SET_HASH(q, hash) do { (q)[0] = (hash); } while (0)
#elif MICROPY_QSTR_BYTES_IN_HASH == 2
    #define Q_HASH_MASK (0xffff)
    #define Q_GET_HASH(q) ((mp_uint_t)(q)[0] | ((mp_uint_t)(q)[1] << 8))
    #define Q_SET_HASH(q, hash) do { (q)[0] = (hash); (q)[1] = (hash) >> 8; } while (0)
#else
    #error unimplemented qstr hash decoding
#endif
#define Q_GET_ALLOC(q)  (MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN + Q_GET_LENGTH(q) + 1)
#define Q_GET_DATA(q)   ((q) + MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN)
65
#if MICROPY_QSTR_BYTES_IN_LEN == 1
66
67
    #define Q_GET_LENGTH(q) ((q)[MICROPY_QSTR_BYTES_IN_HASH])
    #define Q_SET_LENGTH(q, len) do { (q)[MICROPY_QSTR_BYTES_IN_HASH] = (len); } while (0)
68
#elif MICROPY_QSTR_BYTES_IN_LEN == 2
69
70
    #define Q_GET_LENGTH(q) ((q)[MICROPY_QSTR_BYTES_IN_HASH] | ((q)[MICROPY_QSTR_BYTES_IN_HASH + 1] << 8))
    #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)
71
72
73
#else
    #error unimplemented qstr length decoding
#endif
74

75
// this must match the equivalent function in makeqstrdata.py
76
mp_uint_t qstr_compute_hash(const byte *data, mp_uint_t len) {
77
    // djb2 algorithm; see http://www.cse.yorku.ca/~oz/hash.html
78
    mp_uint_t hash = 5381;
79
    for (const byte *top = data + len; data < top; data++) {
80
        hash = ((hash << 5) + hash) ^ (*data); // hash * 33 ^ data
81
    }
82
    hash &= Q_HASH_MASK;
83
84
85
86
87
    // Make sure that valid hash is never zero, zero means "hash not computed"
    if (hash == 0) {
        hash++;
    }
    return hash;
88
89
}

90
STATIC const qstr_pool_t const_pool = {
91
92
93
94
95
    NULL,               // no previous pool
    0,                  // no previous pool
    10,                 // set so that the first dynamically allocated pool is twice this size; must be <= the len (just below)
    MP_QSTR_number_of,  // corresponds to number of strings in array just below
    {
96
#define QDEF(id, str) str,
97
#include "genhdr/qstrdefs.generated.h"
98
#undef QDEF
99
100
101
    },
};

102
void qstr_init(void) {
103
    MP_STATE_VM(last_pool) = (qstr_pool_t*)&const_pool; // we won't modify the const_pool since it has no allocated room left
104
    MP_STATE_VM(qstr_last_chunk) = NULL;
Damien's avatar
Damien committed
105
106
}

107
STATIC const byte *find_qstr(qstr q) {
108
    // search pool for this qstr
109
    for (qstr_pool_t *pool = MP_STATE_VM(last_pool); pool != NULL; pool = pool->prev) {
110
111
112
113
114
115
116
117
118
        if (q >= pool->total_prev_len) {
            return pool->qstrs[q - pool->total_prev_len];
        }
    }

    // not found
    return 0;
}

119
STATIC qstr qstr_add(const byte *q_ptr) {
120
    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));
121
122

    // make sure we have room in the pool for a new qstr
123
124
125
126
127
    if (MP_STATE_VM(last_pool)->len >= MP_STATE_VM(last_pool)->alloc) {
        qstr_pool_t *pool = m_new_obj_var(qstr_pool_t, const char*, MP_STATE_VM(last_pool)->alloc * 2);
        pool->prev = MP_STATE_VM(last_pool);
        pool->total_prev_len = MP_STATE_VM(last_pool)->total_prev_len + MP_STATE_VM(last_pool)->len;
        pool->alloc = MP_STATE_VM(last_pool)->alloc * 2;
128
        pool->len = 0;
129
130
        MP_STATE_VM(last_pool) = pool;
        DEBUG_printf("QSTR: allocate new pool of size %d\n", MP_STATE_VM(last_pool)->alloc);
Damien's avatar
Damien committed
131
    }
132
133

    // add the new qstr
134
    MP_STATE_VM(last_pool)->qstrs[MP_STATE_VM(last_pool)->len++] = q_ptr;
135
136

    // return id for the newly-added qstr
137
    return MP_STATE_VM(last_pool)->total_prev_len + MP_STATE_VM(last_pool)->len - 1;
Damien's avatar
Damien committed
138
139
}

140
qstr qstr_find_strn(const char *str, mp_uint_t str_len) {
141
    // work out hash of str
142
    mp_uint_t str_hash = qstr_compute_hash((const byte*)str, str_len);
143
144

    // search pools for the data
145
    for (qstr_pool_t *pool = MP_STATE_VM(last_pool); pool != NULL; pool = pool->prev) {
146
        for (const byte **q = pool->qstrs, **q_top = pool->qstrs + pool->len; q < q_top; q++) {
147
            if (Q_GET_HASH(*q) == str_hash && Q_GET_LENGTH(*q) == str_len && memcmp(Q_GET_DATA(*q), str, str_len) == 0) {
148
                return pool->total_prev_len + (q - pool->qstrs);
149
            }
Damien's avatar
Damien committed
150
151
        }
    }
152
153
154

    // not found; return null qstr
    return 0;
Damien's avatar
Damien committed
155
156
}

157
158
qstr qstr_from_str(const char *str) {
    return qstr_from_strn(str, strlen(str));
Damien's avatar
Damien committed
159
160
}

161
qstr qstr_from_strn(const char *str, mp_uint_t len) {
162
    assert(len < (1 << (8 * MICROPY_QSTR_BYTES_IN_LEN)));
163
    qstr q = qstr_find_strn(str, len);
164
    if (q == 0) {
165
166
167
        // qstr does not exist in interned pool so need to add it

        // compute number of bytes needed to intern this string
168
        mp_uint_t n_bytes = MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN + len + 1;
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203

        if (MP_STATE_VM(qstr_last_chunk) != NULL && MP_STATE_VM(qstr_last_used) + n_bytes > MP_STATE_VM(qstr_last_alloc)) {
            // not enough room at end of previously interned string so try to grow
            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);
            if (new_p == NULL) {
                // could not grow existing memory; shrink it to fit previous
                (void)m_renew(byte, MP_STATE_VM(qstr_last_chunk), MP_STATE_VM(qstr_last_alloc), MP_STATE_VM(qstr_last_used));
                MP_STATE_VM(qstr_last_chunk) = NULL;
            } else {
                // could grow existing memory
                MP_STATE_VM(qstr_last_alloc) += n_bytes;
            }
        }

        if (MP_STATE_VM(qstr_last_chunk) == NULL) {
            // no existing memory for the interned string so allocate a new chunk
            mp_uint_t al = n_bytes;
            if (al < MICROPY_ALLOC_QSTR_CHUNK_INIT) {
                al = MICROPY_ALLOC_QSTR_CHUNK_INIT;
            }
            MP_STATE_VM(qstr_last_chunk) = m_new_maybe(byte, al);
            if (MP_STATE_VM(qstr_last_chunk) == NULL) {
                // failed to allocate a large chunk so try with exact size
                MP_STATE_VM(qstr_last_chunk) = m_new(byte, n_bytes);
                al = n_bytes;
            }
            MP_STATE_VM(qstr_last_alloc) = al;
            MP_STATE_VM(qstr_last_used) = 0;
        }

        // allocate memory from the chunk for this new interned string's data
        byte *q_ptr = MP_STATE_VM(qstr_last_chunk) + MP_STATE_VM(qstr_last_used);
        MP_STATE_VM(qstr_last_used) += n_bytes;

        // store the interned strings' data
204
        mp_uint_t hash = qstr_compute_hash((const byte*)str, len);
205
        Q_SET_HASH(q_ptr, hash);
206
        Q_SET_LENGTH(q_ptr, len);
207
208
        memcpy(q_ptr + MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN, str, len);
        q_ptr[MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN + len] = '\0';
209
        q = qstr_add(q_ptr);
Damien's avatar
Damien committed
210
    }
211
    return q;
Damien's avatar
Damien committed
212
213
}

214
byte *qstr_build_start(mp_uint_t len, byte **q_ptr) {
215
    assert(len < (1 << (8 * MICROPY_QSTR_BYTES_IN_LEN)));
216
    *q_ptr = m_new(byte, MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN + len + 1);
217
    Q_SET_LENGTH(*q_ptr, len);
218
219
220
221
    return Q_GET_DATA(*q_ptr);
}

qstr qstr_build_end(byte *q_ptr) {
222
    qstr q = qstr_find_strn((const char*)Q_GET_DATA(q_ptr), Q_GET_LENGTH(q_ptr));
223
    if (q == 0) {
224
225
        mp_uint_t len = Q_GET_LENGTH(q_ptr);
        mp_uint_t hash = qstr_compute_hash(Q_GET_DATA(q_ptr), len);
226
227
        Q_SET_HASH(q_ptr, hash);
        q_ptr[MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN + len] = '\0';
228
229
230
        q = qstr_add(q_ptr);
    } else {
        m_del(byte, q_ptr, Q_GET_ALLOC(q_ptr));
231
    }
232
233
234
    return q;
}

235
mp_uint_t qstr_hash(qstr q) {
236
237
238
    return Q_GET_HASH(find_qstr(q));
}

239
mp_uint_t qstr_len(qstr q) {
240
241
242
243
244
245
246
247
248
    const byte *qd = find_qstr(q);
    return Q_GET_LENGTH(qd);
}

// XXX to remove!
const char *qstr_str(qstr q) {
    const byte *qd = find_qstr(q);
    return (const char*)Q_GET_DATA(qd);
}
249

250
const byte *qstr_data(qstr q, mp_uint_t *len) {
251
252
253
    const byte *qd = find_qstr(q);
    *len = Q_GET_LENGTH(qd);
    return Q_GET_DATA(qd);
Damien's avatar
Damien committed
254
}
255

256
void qstr_pool_info(mp_uint_t *n_pool, mp_uint_t *n_qstr, mp_uint_t *n_str_data_bytes, mp_uint_t *n_total_bytes) {
257
258
259
260
    *n_pool = 0;
    *n_qstr = 0;
    *n_str_data_bytes = 0;
    *n_total_bytes = 0;
261
    for (qstr_pool_t *pool = MP_STATE_VM(last_pool); pool != NULL && pool != &const_pool; pool = pool->prev) {
262
263
264
        *n_pool += 1;
        *n_qstr += pool->len;
        for (const byte **q = pool->qstrs, **q_top = pool->qstrs + pool->len; q < q_top; q++) {
265
266
267
            #if MICROPY_ENABLE_GC
            *n_str_data_bytes += gc_nbytes(*q); // this counts actual bytes used in heap
            #else
268
            *n_str_data_bytes += Q_GET_ALLOC(*q);
269
            #endif
270
        }
271
272
273
        #if MICROPY_ENABLE_GC
        *n_total_bytes += gc_nbytes(pool); // this counts actual bytes used in heap
        #else
274
        *n_total_bytes += sizeof(qstr_pool_t) + sizeof(qstr) * pool->alloc;
275
        #endif
276
277
278
    }
    *n_total_bytes += *n_str_data_bytes;
}
279
280
281
282
283

#if MICROPY_PY_MICROPYTHON_MEM_INFO
void qstr_dump_data(void) {
    for (qstr_pool_t *pool = MP_STATE_VM(last_pool); pool != NULL && pool != &const_pool; pool = pool->prev) {
        for (const byte **q = pool->qstrs, **q_top = pool->qstrs + pool->len; q < q_top; q++) {
284
            mp_printf(&mp_plat_print, "Q(%s)\n", Q_GET_DATA(*q));
285
286
287
288
        }
    }
}
#endif