1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2  *
3  * ***** BEGIN LICENSE BLOCK *****
4  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5  *
6  * The contents of this file are subject to the Mozilla Public License Version
7  * 1.1 (the "License"); you may not use this file except in compliance with
8  * the License. You may obtain a copy of the License at
9  * http://www.mozilla.org/MPL/
10  *
11  * Software distributed under the License is distributed on an "AS IS" basis,
12  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13  * for the specific language governing rights and limitations under the
14  * License.
15  *
16  * The Original Code is Mozilla Communicator client code, released
17  * March 31, 1998.
18  *
19  * The Initial Developer of the Original Code is
20  * Netscape Communications Corporation.
21  * Portions created by the Initial Developer are Copyright (C) 1998
22  * the Initial Developer. All Rights Reserved.
23  *
24  * Contributor(s):
25  *
26  * Alternatively, the contents of this file may be used under the terms of
27  * either of the GNU General Public License Version 2 or later (the "GPL"),
28  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
29  * in which case the provisions of the GPL or the LGPL are applicable instead
30  * of those above. If you wish to allow use of your version of this file only
31  * under the terms of either the GPL or the LGPL, and not to allow others to
32  * use your version of this file under the terms of the MPL, indicate your
33  * decision by deleting the provisions above and replace them with the notice
34  * and other provisions required by the GPL or the LGPL. If you do not delete
35  * the provisions above, a recipient may use your version of this file under
36  * the terms of any one of the MPL, the GPL or the LGPL.
37  *
38  * ***** END LICENSE BLOCK ***** */
39 
40 /*
41  * JS atom table.
42  */
43 #include "jsstddef.h"
44 #include <stdlib.h>
45 #include <string.h>
46 #include "jstypes.h"
47 #include "jsutil.h" /* Added by JSIFY */
48 #include "jshash.h" /* Added by JSIFY */
49 #include "jsprf.h"
50 #include "jsapi.h"
51 #include "jsatom.h"
52 #include "jscntxt.h"
53 #include "jsgc.h"
54 #include "jslock.h"
55 #include "jsnum.h"
56 #include "jsopcode.h"
57 #include "jsstr.h"
58 
59 JS_FRIEND_API(const char *)
js_AtomToPrintableString(JSContext * cx,JSAtom * atom)60 js_AtomToPrintableString(JSContext *cx, JSAtom *atom)
61 {
62     JSString *str;
63     const char *bytes;
64 
65     str = js_QuoteString(cx, ATOM_TO_STRING(atom), 0);
66     if (!str)
67         return NULL;
68     bytes = js_GetStringBytes(str);
69     if (!bytes)
70         JS_ReportOutOfMemory(cx);
71     return bytes;
72 }
73 
74 extern const char js_Error_str[];       /* trivial, from jsexn.h */
75 
76 /*
77  * Keep this in sync with jspubtd.h -- an assertion below will insist that
78  * its length match the JSType enum's JSTYPE_LIMIT limit value.
79  */
80 const char *js_type_str[] = {
81     "undefined",
82     "object",
83     "function",
84     "string",
85     "number",
86     "boolean",
87 };
88 
89 const char *js_boolean_str[] = {
90     js_false_str,
91     js_true_str
92 };
93 
94 const char js_Arguments_str[]       = "Arguments";
95 const char js_Array_str[]           = "Array";
96 const char js_Boolean_str[]         = "Boolean";
97 const char js_Call_str[]            = "Call";
98 const char js_Date_str[]            = "Date";
99 const char js_Function_str[]        = "Function";
100 const char js_Math_str[]            = "Math";
101 const char js_Number_str[]          = "Number";
102 const char js_Object_str[]          = "Object";
103 const char js_RegExp_str[]          = "RegExp";
104 const char js_Script_str[]          = "Script";
105 const char js_String_str[]          = "String";
106 const char js_anonymous_str[]       = "anonymous";
107 const char js_arguments_str[]       = "arguments";
108 const char js_arity_str[]           = "arity";
109 const char js_callee_str[]          = "callee";
110 const char js_caller_str[]          = "caller";
111 const char js_class_prototype_str[] = "prototype";
112 const char js_constructor_str[]     = "constructor";
113 const char js_count_str[]           = "__count__";
114 const char js_eval_str[]            = "eval";
115 const char js_getter_str[]          = "getter";
116 const char js_get_str[]             = "get";
117 const char js_index_str[]           = "index";
118 const char js_input_str[]           = "input";
119 const char js_length_str[]          = "length";
120 const char js_name_str[]            = "name";
121 const char js_noSuchMethod_str[]    = "__noSuchMethod__";
122 const char js_parent_str[]          = "__parent__";
123 const char js_proto_str[]           = "__proto__";
124 const char js_setter_str[]          = "setter";
125 const char js_set_str[]             = "set";
126 const char js_toSource_str[]        = "toSource";
127 const char js_toString_str[]        = "toString";
128 const char js_toLocaleString_str[]  = "toLocaleString";
129 const char js_valueOf_str[]         = "valueOf";
130 
131 #ifdef NARCISSUS
132 const char js_call_str[]             = "__call__";
133 const char js_construct_str[]        = "__construct__";
134 const char js_hasInstance_str[]      = "__hasInstance__";
135 const char js_ExecutionContext_str[] = "ExecutionContext";
136 const char js_current_str[]          = "current";
137 #endif
138 
139 #define HASH_OBJECT(o)  ((JSHashNumber)(o) >> JSVAL_TAGBITS)
140 #define HASH_INT(i)     ((JSHashNumber)(i))
141 #define HASH_DOUBLE(dp) ((JSHashNumber)(JSDOUBLE_HI32(*dp) ^ JSDOUBLE_LO32(*dp)))
142 #define HASH_BOOLEAN(b) ((JSHashNumber)(b))
143 
144 JS_STATIC_DLL_CALLBACK(JSHashNumber)
js_hash_atom_key(const void * key)145 js_hash_atom_key(const void *key)
146 {
147     jsval v;
148     jsdouble *dp;
149 
150     /* Order JSVAL_IS_* tests by likelihood of success. */
151     v = (jsval)key;
152     if (JSVAL_IS_STRING(v))
153         return js_HashString(JSVAL_TO_STRING(v));
154     if (JSVAL_IS_INT(v))
155         return HASH_INT(JSVAL_TO_INT(v));
156     if (JSVAL_IS_DOUBLE(v)) {
157         dp = JSVAL_TO_DOUBLE(v);
158         return HASH_DOUBLE(dp);
159     }
160     if (JSVAL_IS_OBJECT(v))
161         return HASH_OBJECT(JSVAL_TO_OBJECT(v));
162     if (JSVAL_IS_BOOLEAN(v))
163         return HASH_BOOLEAN(JSVAL_TO_BOOLEAN(v));
164     return (JSHashNumber)v;
165 }
166 
167 JS_STATIC_DLL_CALLBACK(intN)
js_compare_atom_keys(const void * k1,const void * k2)168 js_compare_atom_keys(const void *k1, const void *k2)
169 {
170     jsval v1, v2;
171 
172     v1 = (jsval)k1, v2 = (jsval)k2;
173     if (JSVAL_IS_STRING(v1) && JSVAL_IS_STRING(v2))
174         return !js_CompareStrings(JSVAL_TO_STRING(v1), JSVAL_TO_STRING(v2));
175     if (JSVAL_IS_DOUBLE(v1) && JSVAL_IS_DOUBLE(v2)) {
176         double d1 = *JSVAL_TO_DOUBLE(v1);
177         double d2 = *JSVAL_TO_DOUBLE(v2);
178         if (JSDOUBLE_IS_NaN(d1))
179             return JSDOUBLE_IS_NaN(d2);
180 #if defined(XP_WIN)
181         /* XXX MSVC miscompiles such that (NaN == 0) */
182         if (JSDOUBLE_IS_NaN(d2))
183             return JS_FALSE;
184 #endif
185         return d1 == d2;
186     }
187     return v1 == v2;
188 }
189 
190 JS_STATIC_DLL_CALLBACK(int)
js_compare_stub(const void * v1,const void * v2)191 js_compare_stub(const void *v1, const void *v2)
192 {
193     return 1;
194 }
195 
196 /* These next two are exported to jsscript.c and used similarly there. */
197 void * JS_DLL_CALLBACK
js_alloc_table_space(void * priv,size_t size)198 js_alloc_table_space(void *priv, size_t size)
199 {
200     return malloc(size);
201 }
202 
203 void JS_DLL_CALLBACK
js_free_table_space(void * priv,void * item)204 js_free_table_space(void *priv, void *item)
205 {
206     free(item);
207 }
208 
209 JS_STATIC_DLL_CALLBACK(JSHashEntry *)
js_alloc_atom(void * priv,const void * key)210 js_alloc_atom(void *priv, const void *key)
211 {
212     JSAtomState *state = (JSAtomState *) priv;
213     JSAtom *atom;
214 
215     atom = (JSAtom *) malloc(sizeof(JSAtom));
216     if (!atom)
217         return NULL;
218 #ifdef JS_THREADSAFE
219     state->tablegen++;
220 #endif
221     atom->entry.key = key;
222     atom->entry.value = NULL;
223     atom->flags = 0;
224     atom->number = state->number++;
225     return &atom->entry;
226 }
227 
228 JS_STATIC_DLL_CALLBACK(void)
js_free_atom(void * priv,JSHashEntry * he,uintN flag)229 js_free_atom(void *priv, JSHashEntry *he, uintN flag)
230 {
231     if (flag != HT_FREE_ENTRY)
232         return;
233 #ifdef JS_THREADSAFE
234     ((JSAtomState *)priv)->tablegen++;
235 #endif
236     free(he);
237 }
238 
239 static JSHashAllocOps atom_alloc_ops = {
240     js_alloc_table_space,   js_free_table_space,
241     js_alloc_atom,          js_free_atom
242 };
243 
244 #define JS_ATOM_HASH_SIZE   1024
245 
246 JSBool
js_InitAtomState(JSContext * cx,JSAtomState * state)247 js_InitAtomState(JSContext *cx, JSAtomState *state)
248 {
249     state->table = JS_NewHashTable(JS_ATOM_HASH_SIZE, js_hash_atom_key,
250                                    js_compare_atom_keys, js_compare_stub,
251                                    &atom_alloc_ops, state);
252     if (!state->table) {
253         JS_ReportOutOfMemory(cx);
254         return JS_FALSE;
255     }
256 
257     state->runtime = cx->runtime;
258 #ifdef JS_THREADSAFE
259     js_InitLock(&state->lock);
260     state->tablegen = 0;
261 #endif
262 
263     if (!js_InitPinnedAtoms(cx, state)) {
264         js_FreeAtomState(cx, state);
265         return JS_FALSE;
266     }
267     return JS_TRUE;
268 }
269 
270 JSBool
js_InitPinnedAtoms(JSContext * cx,JSAtomState * state)271 js_InitPinnedAtoms(JSContext *cx, JSAtomState *state)
272 {
273     uintN i;
274 
275 #define FROB(lval,str)                                                        \
276     JS_BEGIN_MACRO                                                            \
277         if (!(state->lval = js_Atomize(cx, str, strlen(str), ATOM_PINNED)))   \
278             return JS_FALSE;                                                  \
279     JS_END_MACRO
280 
281     JS_ASSERT(sizeof js_type_str / sizeof js_type_str[0] == JSTYPE_LIMIT);
282     for (i = 0; i < JSTYPE_LIMIT; i++)
283         FROB(typeAtoms[i],        js_type_str[i]);
284 
285     FROB(booleanAtoms[0],         js_false_str);
286     FROB(booleanAtoms[1],         js_true_str);
287     FROB(nullAtom,                js_null_str);
288 
289     FROB(ArgumentsAtom,           js_Arguments_str);
290     FROB(ArrayAtom,               js_Array_str);
291     FROB(BooleanAtom,             js_Boolean_str);
292     FROB(CallAtom,                js_Call_str);
293     FROB(DateAtom,                js_Date_str);
294     FROB(ErrorAtom,               js_Error_str);
295     FROB(FunctionAtom,            js_Function_str);
296     FROB(MathAtom,                js_Math_str);
297     FROB(NumberAtom,              js_Number_str);
298     FROB(ObjectAtom,              js_Object_str);
299     FROB(RegExpAtom,              js_RegExp_str);
300     FROB(ScriptAtom,              js_Script_str);
301     FROB(StringAtom,              js_String_str);
302     FROB(anonymousAtom,           js_anonymous_str);
303     FROB(argumentsAtom,           js_arguments_str);
304     FROB(arityAtom,               js_arity_str);
305     FROB(calleeAtom,              js_callee_str);
306     FROB(callerAtom,              js_caller_str);
307     FROB(classPrototypeAtom,      js_class_prototype_str);
308     FROB(constructorAtom,         js_constructor_str);
309     FROB(countAtom,               js_count_str);
310     FROB(evalAtom,                js_eval_str);
311     FROB(getAtom,                 js_get_str);
312     FROB(getterAtom,              js_getter_str);
313     FROB(indexAtom,               js_index_str);
314     FROB(inputAtom,               js_input_str);
315     FROB(lengthAtom,              js_length_str);
316     FROB(nameAtom,                js_name_str);
317     FROB(noSuchMethodAtom,        js_noSuchMethod_str);
318     FROB(parentAtom,              js_parent_str);
319     FROB(protoAtom,               js_proto_str);
320     FROB(setAtom,                 js_set_str);
321     FROB(setterAtom,              js_setter_str);
322     FROB(toSourceAtom,            js_toSource_str);
323     FROB(toStringAtom,            js_toString_str);
324     FROB(toLocaleStringAtom,      js_toLocaleString_str);
325     FROB(valueOfAtom,             js_valueOf_str);
326 
327 #ifdef NARCISSUS
328     FROB(callAtom,                js_call_str);
329     FROB(constructAtom,           js_construct_str);
330     FROB(hasInstanceAtom,         js_hasInstance_str);
331     FROB(ExecutionContextAtom,    js_ExecutionContext_str);
332     FROB(currentAtom,             js_current_str);
333 #endif
334 
335 #undef FROB
336 
337     memset(&state->lazy, 0, sizeof state->lazy);
338     return JS_TRUE;
339 }
340 
341 /* NB: cx unused; js_FinishAtomState calls us with null cx. */
342 void
js_FreeAtomState(JSContext * cx,JSAtomState * state)343 js_FreeAtomState(JSContext *cx, JSAtomState *state)
344 {
345     if (state->table)
346         JS_HashTableDestroy(state->table);
347 #ifdef JS_THREADSAFE
348     js_FinishLock(&state->lock);
349 #endif
350     memset(state, 0, sizeof *state);
351 }
352 
353 typedef struct UninternArgs {
354     JSRuntime   *rt;
355     jsatomid    leaks;
356 } UninternArgs;
357 
358 JS_STATIC_DLL_CALLBACK(intN)
js_atom_uninterner(JSHashEntry * he,intN i,void * arg)359 js_atom_uninterner(JSHashEntry *he, intN i, void *arg)
360 {
361     JSAtom *atom;
362     UninternArgs *args;
363 
364     atom = (JSAtom *)he;
365     args = (UninternArgs *)arg;
366     if (ATOM_IS_STRING(atom))
367         js_FinalizeStringRT(args->rt, ATOM_TO_STRING(atom));
368     else if (ATOM_IS_OBJECT(atom))
369         args->leaks++;
370     return HT_ENUMERATE_NEXT;
371 }
372 
373 void
js_FinishAtomState(JSAtomState * state)374 js_FinishAtomState(JSAtomState *state)
375 {
376     UninternArgs args;
377 
378     if (!state->table)
379         return;
380     args.rt = state->runtime;
381     args.leaks = 0;
382     JS_HashTableEnumerateEntries(state->table, js_atom_uninterner, &args);
383 #ifdef DEBUG
384     if (args.leaks != 0) {
385         fprintf(stderr,
386 "JS engine warning: %lu atoms remain after destroying the JSRuntime.\n"
387 "                   These atoms may point to freed memory. Things reachable\n"
388 "                   through them have not been finalized.\n",
389                 (unsigned long) args.leaks);
390     }
391 #endif
392     js_FreeAtomState(NULL, state);
393 }
394 
395 typedef struct MarkArgs {
396     uintN           gcflags;
397     JSGCThingMarker mark;
398     void            *data;
399 } MarkArgs;
400 
401 JS_STATIC_DLL_CALLBACK(intN)
js_atom_marker(JSHashEntry * he,intN i,void * arg)402 js_atom_marker(JSHashEntry *he, intN i, void *arg)
403 {
404     JSAtom *atom;
405     MarkArgs *args;
406     jsval key;
407 
408     atom = (JSAtom *)he;
409     args = (MarkArgs *)arg;
410     if ((atom->flags & (ATOM_PINNED | ATOM_INTERNED)) ||
411         (args->gcflags & GC_KEEP_ATOMS)) {
412         atom->flags |= ATOM_MARK;
413         key = ATOM_KEY(atom);
414         if (JSVAL_IS_GCTHING(key))
415             args->mark(JSVAL_TO_GCTHING(key), args->data);
416     }
417     return HT_ENUMERATE_NEXT;
418 }
419 
420 void
js_MarkAtomState(JSAtomState * state,uintN gcflags,JSGCThingMarker mark,void * data)421 js_MarkAtomState(JSAtomState *state, uintN gcflags, JSGCThingMarker mark,
422                  void *data)
423 {
424     MarkArgs args;
425 
426     if (!state->table)
427         return;
428     args.gcflags = gcflags;
429     args.mark = mark;
430     args.data = data;
431     JS_HashTableEnumerateEntries(state->table, js_atom_marker, &args);
432 }
433 
434 JS_STATIC_DLL_CALLBACK(intN)
js_atom_sweeper(JSHashEntry * he,intN i,void * arg)435 js_atom_sweeper(JSHashEntry *he, intN i, void *arg)
436 {
437     JSAtom *atom;
438     JSAtomState *state;
439 
440     atom = (JSAtom *)he;
441     if (atom->flags & ATOM_MARK) {
442         atom->flags &= ~ATOM_MARK;
443         state = (JSAtomState *)arg;
444         state->liveAtoms++;
445         return HT_ENUMERATE_NEXT;
446     }
447     JS_ASSERT((atom->flags & (ATOM_PINNED | ATOM_INTERNED)) == 0);
448     atom->entry.key = NULL;
449     atom->flags = 0;
450     return HT_ENUMERATE_REMOVE;
451 }
452 
453 void
js_SweepAtomState(JSAtomState * state)454 js_SweepAtomState(JSAtomState *state)
455 {
456     state->liveAtoms = 0;
457     if (state->table)
458         JS_HashTableEnumerateEntries(state->table, js_atom_sweeper, state);
459 }
460 
461 JS_STATIC_DLL_CALLBACK(intN)
js_atom_unpinner(JSHashEntry * he,intN i,void * arg)462 js_atom_unpinner(JSHashEntry *he, intN i, void *arg)
463 {
464     JSAtom *atom;
465 
466     atom = (JSAtom *)he;
467     atom->flags &= ~ATOM_PINNED;
468     return HT_ENUMERATE_NEXT;
469 }
470 
471 void
js_UnpinPinnedAtoms(JSAtomState * state)472 js_UnpinPinnedAtoms(JSAtomState *state)
473 {
474     if (state->table)
475         JS_HashTableEnumerateEntries(state->table, js_atom_unpinner, NULL);
476 }
477 
478 static JSAtom *
js_AtomizeHashedKey(JSContext * cx,jsval key,JSHashNumber keyHash,uintN flags)479 js_AtomizeHashedKey(JSContext *cx, jsval key, JSHashNumber keyHash, uintN flags)
480 {
481     JSAtomState *state;
482     JSHashTable *table;
483     JSHashEntry *he, **hep;
484     JSAtom *atom;
485 
486     state = &cx->runtime->atomState;
487     JS_LOCK(&state->lock, cx);
488     table = state->table;
489     hep = JS_HashTableRawLookup(table, keyHash, (void *)key);
490     if ((he = *hep) == NULL) {
491         he = JS_HashTableRawAdd(table, hep, keyHash, (void *)key, NULL);
492         if (!he) {
493             JS_ReportOutOfMemory(cx);
494             atom = NULL;
495             goto out;
496         }
497     }
498 
499     atom = (JSAtom *)he;
500     atom->flags |= flags;
501     cx->lastAtom = atom;
502 out:
503     JS_UNLOCK(&state->lock,cx);
504     return atom;
505 }
506 
507 JSAtom *
js_AtomizeObject(JSContext * cx,JSObject * obj,uintN flags)508 js_AtomizeObject(JSContext *cx, JSObject *obj, uintN flags)
509 {
510     jsval key;
511     JSHashNumber keyHash;
512 
513     /* XXX must be set in the following order or MSVC1.52 will crash */
514     keyHash = HASH_OBJECT(obj);
515     key = OBJECT_TO_JSVAL(obj);
516     return js_AtomizeHashedKey(cx, key, keyHash, flags);
517 }
518 
519 JSAtom *
js_AtomizeBoolean(JSContext * cx,JSBool b,uintN flags)520 js_AtomizeBoolean(JSContext *cx, JSBool b, uintN flags)
521 {
522     jsval key;
523     JSHashNumber keyHash;
524 
525     key = BOOLEAN_TO_JSVAL(b);
526     keyHash = HASH_BOOLEAN(b);
527     return js_AtomizeHashedKey(cx, key, keyHash, flags);
528 }
529 
530 JSAtom *
js_AtomizeInt(JSContext * cx,jsint i,uintN flags)531 js_AtomizeInt(JSContext *cx, jsint i, uintN flags)
532 {
533     jsval key;
534     JSHashNumber keyHash;
535 
536     key = INT_TO_JSVAL(i);
537     keyHash = HASH_INT(i);
538     return js_AtomizeHashedKey(cx, key, keyHash, flags);
539 }
540 
541 /* Worst-case alignment grain and aligning macro for 2x-sized buffer. */
542 #define ALIGNMENT(t)    JS_MAX(JSVAL_ALIGN, sizeof(t))
543 #define ALIGN(b,t)      ((t*) &(b)[ALIGNMENT(t) - (jsuword)(b) % ALIGNMENT(t)])
544 
545 JSAtom *
js_AtomizeDouble(JSContext * cx,jsdouble d,uintN flags)546 js_AtomizeDouble(JSContext *cx, jsdouble d, uintN flags)
547 {
548     jsdouble *dp;
549     JSHashNumber keyHash;
550     jsval key;
551     JSAtomState *state;
552     JSHashTable *table;
553     JSHashEntry *he, **hep;
554     JSAtom *atom;
555     char buf[2 * ALIGNMENT(double)];
556 
557     dp = ALIGN(buf, double);
558     *dp = d;
559     keyHash = HASH_DOUBLE(dp);
560     key = DOUBLE_TO_JSVAL(dp);
561     state = &cx->runtime->atomState;
562     JS_LOCK(&state->lock, cx);
563     table = state->table;
564     hep = JS_HashTableRawLookup(table, keyHash, (void *)key);
565     if ((he = *hep) == NULL) {
566 #ifdef JS_THREADSAFE
567         uint32 gen = state->tablegen;
568 #endif
569         JS_UNLOCK(&state->lock,cx);
570         if (!js_NewDoubleValue(cx, d, &key))
571             return NULL;
572         JS_LOCK(&state->lock, cx);
573 #ifdef JS_THREADSAFE
574         if (state->tablegen != gen) {
575             hep = JS_HashTableRawLookup(table, keyHash, (void *)key);
576             if ((he = *hep) != NULL) {
577                 atom = (JSAtom *)he;
578                 goto out;
579             }
580         }
581 #endif
582         he = JS_HashTableRawAdd(table, hep, keyHash, (void *)key, NULL);
583         if (!he) {
584             JS_ReportOutOfMemory(cx);
585             atom = NULL;
586             goto out;
587         }
588     }
589 
590     atom = (JSAtom *)he;
591     atom->flags |= flags;
592     cx->lastAtom = atom;
593 out:
594     JS_UNLOCK(&state->lock,cx);
595     return atom;
596 }
597 
598 JSAtom *
js_AtomizeString(JSContext * cx,JSString * str,uintN flags)599 js_AtomizeString(JSContext *cx, JSString *str, uintN flags)
600 {
601     JSHashNumber keyHash;
602     jsval key;
603     JSAtomState *state;
604     JSHashTable *table;
605     JSHashEntry *he, **hep;
606     JSAtom *atom;
607 
608     keyHash = js_HashString(str);
609     key = STRING_TO_JSVAL(str);
610     state = &cx->runtime->atomState;
611     JS_LOCK(&state->lock, cx);
612     table = state->table;
613     hep = JS_HashTableRawLookup(table, keyHash, (void *)key);
614     if ((he = *hep) == NULL) {
615 #ifdef JS_THREADSAFE
616         uint32 gen = state->tablegen;
617         JS_UNLOCK(&state->lock, cx);
618 #endif
619 
620         if (flags & ATOM_TMPSTR) {
621             str = (flags & ATOM_NOCOPY)
622                   ? js_NewString(cx, str->chars, str->length, 0)
623                   : js_NewStringCopyN(cx, str->chars, str->length, 0);
624             if (!str)
625                 return NULL;
626             key = STRING_TO_JSVAL(str);
627         } else {
628             if (!JS_MakeStringImmutable(cx, str))
629                 return NULL;
630         }
631 
632 #ifdef JS_THREADSAFE
633         JS_LOCK(&state->lock, cx);
634         if (state->tablegen != gen) {
635             hep = JS_HashTableRawLookup(table, keyHash, (void *)key);
636             if ((he = *hep) != NULL) {
637                 atom = (JSAtom *)he;
638                 if (flags & ATOM_NOCOPY)
639                     str->chars = NULL;
640                 goto out;
641             }
642         }
643 #endif
644 
645         he = JS_HashTableRawAdd(table, hep, keyHash, (void *)key, NULL);
646         if (!he) {
647             JS_ReportOutOfMemory(cx);
648             atom = NULL;
649             goto out;
650         }
651     }
652 
653     atom = (JSAtom *)he;
654     atom->flags |= flags & (ATOM_PINNED | ATOM_INTERNED);
655     cx->lastAtom = atom;
656 out:
657     JS_UNLOCK(&state->lock,cx);
658     return atom;
659 }
660 
661 JS_FRIEND_API(JSAtom *)
js_Atomize(JSContext * cx,const char * bytes,size_t length,uintN flags)662 js_Atomize(JSContext *cx, const char *bytes, size_t length, uintN flags)
663 {
664     jschar *chars;
665     JSString *str;
666     JSAtom *atom;
667     char buf[2 * ALIGNMENT(JSString)];
668 
669     /*
670      * Avoiding the malloc in js_InflateString on shorter strings saves us
671      * over 20,000 malloc calls on mozilla browser startup. This compares to
672      * only 131 calls where the string is longer than a 31 char (net) buffer.
673      * The vast majority of atomized strings are already in the hashtable. So
674      * js_AtomizeString rarely has to copy the temp string we make.
675      */
676 #define ATOMIZE_BUF_MAX 32
677     jschar inflated[ATOMIZE_BUF_MAX];
678 
679     if (length < ATOMIZE_BUF_MAX) {
680         js_InflateStringToBuffer(inflated, bytes, length);
681         chars = inflated;
682     } else {
683         chars = js_InflateString(cx, bytes, length);
684         if (!chars)
685             return NULL;
686         flags |= ATOM_NOCOPY;
687     }
688 
689     str = ALIGN(buf, JSString);
690 
691     str->chars = chars;
692     str->length = length;
693     atom = js_AtomizeString(cx, str, ATOM_TMPSTR | flags);
694     if (chars != inflated && (!atom || ATOM_TO_STRING(atom)->chars != chars))
695         JS_free(cx, chars);
696     return atom;
697 }
698 
699 JS_FRIEND_API(JSAtom *)
js_AtomizeChars(JSContext * cx,const jschar * chars,size_t length,uintN flags)700 js_AtomizeChars(JSContext *cx, const jschar *chars, size_t length, uintN flags)
701 {
702     JSString *str;
703     char buf[2 * ALIGNMENT(JSString)];
704 
705     str = ALIGN(buf, JSString);
706     str->chars = (jschar *)chars;
707     str->length = length;
708     return js_AtomizeString(cx, str, ATOM_TMPSTR | flags);
709 }
710 
711 JSAtom *
js_AtomizeValue(JSContext * cx,jsval value,uintN flags)712 js_AtomizeValue(JSContext *cx, jsval value, uintN flags)
713 {
714     if (JSVAL_IS_STRING(value))
715         return js_AtomizeString(cx, JSVAL_TO_STRING(value), flags);
716     if (JSVAL_IS_INT(value))
717         return js_AtomizeInt(cx, JSVAL_TO_INT(value), flags);
718     if (JSVAL_IS_DOUBLE(value))
719         return js_AtomizeDouble(cx, *JSVAL_TO_DOUBLE(value), flags);
720     if (JSVAL_IS_OBJECT(value))
721         return js_AtomizeObject(cx, JSVAL_TO_OBJECT(value), flags);
722     if (JSVAL_IS_BOOLEAN(value))
723         return js_AtomizeBoolean(cx, JSVAL_TO_BOOLEAN(value), flags);
724     return js_AtomizeHashedKey(cx, value, (JSHashNumber)value, flags);
725 }
726 
727 JSAtom *
js_ValueToStringAtom(JSContext * cx,jsval v)728 js_ValueToStringAtom(JSContext *cx, jsval v)
729 {
730     JSString *str;
731 
732     str = js_ValueToString(cx, v);
733     if (!str)
734         return NULL;
735     return js_AtomizeString(cx, str, 0);
736 }
737 
738 JS_STATIC_DLL_CALLBACK(JSHashNumber)
js_hash_atom_ptr(const void * key)739 js_hash_atom_ptr(const void *key)
740 {
741     const JSAtom *atom = key;
742     return atom->number;
743 }
744 
745 JS_STATIC_DLL_CALLBACK(void *)
js_alloc_temp_space(void * priv,size_t size)746 js_alloc_temp_space(void *priv, size_t size)
747 {
748     JSContext *cx = priv;
749     void *space;
750 
751     JS_ARENA_ALLOCATE(space, &cx->tempPool, size);
752     if (!space)
753         JS_ReportOutOfMemory(cx);
754     return space;
755 }
756 
757 JS_STATIC_DLL_CALLBACK(void)
js_free_temp_space(void * priv,void * item)758 js_free_temp_space(void *priv, void *item)
759 {
760 }
761 
762 JS_STATIC_DLL_CALLBACK(JSHashEntry *)
js_alloc_temp_entry(void * priv,const void * key)763 js_alloc_temp_entry(void *priv, const void *key)
764 {
765     JSContext *cx = priv;
766     JSAtomListElement *ale;
767 
768     JS_ARENA_ALLOCATE_TYPE(ale, JSAtomListElement, &cx->tempPool);
769     if (!ale) {
770         JS_ReportOutOfMemory(cx);
771         return NULL;
772     }
773     return &ale->entry;
774 }
775 
776 JS_STATIC_DLL_CALLBACK(void)
js_free_temp_entry(void * priv,JSHashEntry * he,uintN flag)777 js_free_temp_entry(void *priv, JSHashEntry *he, uintN flag)
778 {
779 }
780 
781 static JSHashAllocOps temp_alloc_ops = {
782     js_alloc_temp_space,    js_free_temp_space,
783     js_alloc_temp_entry,    js_free_temp_entry
784 };
785 
786 JSAtomListElement *
js_IndexAtom(JSContext * cx,JSAtom * atom,JSAtomList * al)787 js_IndexAtom(JSContext *cx, JSAtom *atom, JSAtomList *al)
788 {
789     JSAtomListElement *ale, *ale2, *next;
790     JSHashEntry **hep;
791 
792     ATOM_LIST_LOOKUP(ale, hep, al, atom);
793     if (!ale) {
794         if (al->count < 10) {
795             /* Few enough for linear search, no hash table needed. */
796             JS_ASSERT(!al->table);
797             ale = (JSAtomListElement *)js_alloc_temp_entry(cx, atom);
798             if (!ale)
799                 return NULL;
800             ALE_SET_ATOM(ale, atom);
801             ALE_SET_NEXT(ale, al->list);
802             al->list = ale;
803         } else {
804             /* We want to hash.  Have we already made a hash table? */
805             if (!al->table) {
806                 /* No hash table yet, so hep had better be null! */
807                 JS_ASSERT(!hep);
808                 al->table = JS_NewHashTable(8, js_hash_atom_ptr,
809                                             JS_CompareValues, JS_CompareValues,
810                                             &temp_alloc_ops, cx);
811                 if (!al->table)
812                     return NULL;
813 
814                 /* Insert each ale on al->list into the new hash table. */
815                 for (ale2 = al->list; ale2; ale2 = next) {
816                     next = ALE_NEXT(ale2);
817                     ale2->entry.keyHash = ALE_ATOM(ale2)->number;
818                     hep = JS_HashTableRawLookup(al->table, ale2->entry.keyHash,
819                                                 ale2->entry.key);
820                     ALE_SET_NEXT(ale2, *hep);
821                     *hep = &ale2->entry;
822                 }
823                 al->list = NULL;
824 
825                 /* Set hep for insertion of atom's ale, immediately below. */
826                 hep = JS_HashTableRawLookup(al->table, atom->number, atom);
827             }
828 
829             /* Finally, add an entry for atom into the hash bucket at hep. */
830             ale = (JSAtomListElement *)
831                   JS_HashTableRawAdd(al->table, hep, atom->number, atom, NULL);
832             if (!ale)
833                 return NULL;
834         }
835 
836         ALE_SET_INDEX(ale, al->count++);
837     }
838     return ale;
839 }
840 
841 JS_FRIEND_API(JSAtom *)
js_GetAtom(JSContext * cx,JSAtomMap * map,jsatomid i)842 js_GetAtom(JSContext *cx, JSAtomMap *map, jsatomid i)
843 {
844     JSAtom *atom;
845     static JSAtom dummy;
846 
847     JS_ASSERT(map->vector && i < map->length);
848     if (!map->vector || i >= map->length) {
849         char numBuf[12];
850         JS_snprintf(numBuf, sizeof numBuf, "%lu", (unsigned long)i);
851         JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
852                              JSMSG_BAD_ATOMIC_NUMBER, numBuf);
853         return &dummy;
854     }
855     atom = map->vector[i];
856     JS_ASSERT(atom);
857     return atom;
858 }
859 
860 JS_STATIC_DLL_CALLBACK(intN)
js_map_atom(JSHashEntry * he,intN i,void * arg)861 js_map_atom(JSHashEntry *he, intN i, void *arg)
862 {
863     JSAtomListElement *ale = (JSAtomListElement *)he;
864     JSAtom **vector = arg;
865 
866     vector[ALE_INDEX(ale)] = ALE_ATOM(ale);
867     return HT_ENUMERATE_NEXT;
868 }
869 
870 #ifdef DEBUG
871 jsrefcount js_atom_map_count;
872 jsrefcount js_atom_map_hash_table_count;
873 #endif
874 
875 JS_FRIEND_API(JSBool)
js_InitAtomMap(JSContext * cx,JSAtomMap * map,JSAtomList * al)876 js_InitAtomMap(JSContext *cx, JSAtomMap *map, JSAtomList *al)
877 {
878     JSAtom **vector;
879     JSAtomListElement *ale;
880     uint32 count;
881 
882 #ifdef DEBUG
883     JS_ATOMIC_INCREMENT(&js_atom_map_count);
884 #endif
885     ale = al->list;
886     if (!ale && !al->table) {
887         map->vector = NULL;
888         map->length = 0;
889         return JS_TRUE;
890     }
891 
892     count = al->count;
893     if (count >= ATOM_INDEX_LIMIT) {
894         JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
895                              JSMSG_TOO_MANY_LITERALS);
896         return JS_FALSE;
897     }
898     vector = (JSAtom **) JS_malloc(cx, (size_t) count * sizeof *vector);
899     if (!vector)
900         return JS_FALSE;
901 
902     if (al->table) {
903 #ifdef DEBUG
904         JS_ATOMIC_INCREMENT(&js_atom_map_hash_table_count);
905 #endif
906         JS_HashTableEnumerateEntries(al->table, js_map_atom, vector);
907     } else {
908         do {
909             vector[ALE_INDEX(ale)] = ALE_ATOM(ale);
910         } while ((ale = ALE_NEXT(ale)) != NULL);
911     }
912     ATOM_LIST_INIT(al);
913 
914     map->vector = vector;
915     map->length = (jsatomid)count;
916     return JS_TRUE;
917 }
918 
919 JS_FRIEND_API(void)
js_FreeAtomMap(JSContext * cx,JSAtomMap * map)920 js_FreeAtomMap(JSContext *cx, JSAtomMap *map)
921 {
922     if (map->vector) {
923         JS_free(cx, map->vector);
924         map->vector = NULL;
925     }
926     map->length = 0;
927 }
928