Bug 617935: Check string lengths using StringBuffer. (r=lw)
[mozilla-central.git] / js / src / jsobj.h
blob46add1b2ec91f690fc014545bf9de66e90658965
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 * vim: set ts=8 sw=4 et tw=78:
4 * ***** BEGIN LICENSE BLOCK *****
5 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
7 * The contents of this file are subject to the Mozilla Public License Version
8 * 1.1 (the "License"); you may not use this file except in compliance with
9 * the License. You may obtain a copy of the License at
10 * http://www.mozilla.org/MPL/
12 * Software distributed under the License is distributed on an "AS IS" basis,
13 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14 * for the specific language governing rights and limitations under the
15 * License.
17 * The Original Code is Mozilla Communicator client code, released
18 * March 31, 1998.
20 * The Initial Developer of the Original Code is
21 * Netscape Communications Corporation.
22 * Portions created by the Initial Developer are Copyright (C) 1998
23 * the Initial Developer. All Rights Reserved.
25 * Contributor(s):
27 * Alternatively, the contents of this file may be used under the terms of
28 * either of the GNU General Public License Version 2 or later (the "GPL"),
29 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
30 * in which case the provisions of the GPL or the LGPL are applicable instead
31 * of those above. If you wish to allow use of your version of this file only
32 * under the terms of either the GPL or the LGPL, and not to allow others to
33 * use your version of this file under the terms of the MPL, indicate your
34 * decision by deleting the provisions above and replace them with the notice
35 * and other provisions required by the GPL or the LGPL. If you do not delete
36 * the provisions above, a recipient may use your version of this file under
37 * the terms of any one of the MPL, the GPL or the LGPL.
39 * ***** END LICENSE BLOCK ***** */
41 #ifndef jsobj_h___
42 #define jsobj_h___
44 * JS object definitions.
46 * A JS object consists of a possibly-shared object descriptor containing
47 * ordered property names, called the map; and a dense vector of property
48 * values, called slots. The map/slot pointer pair is GC'ed, while the map
49 * is reference counted and the slot vector is malloc'ed.
51 #include "jsapi.h"
52 #include "jshash.h"
53 #include "jspubtd.h"
54 #include "jsprvtd.h"
55 #include "jslock.h"
56 #include "jsvalue.h"
57 #include "jsvector.h"
58 #include "jscell.h"
60 namespace js {
62 class JSProxyHandler;
63 class AutoPropDescArrayRooter;
65 namespace mjit {
66 class Compiler;
69 static inline PropertyOp
70 CastAsPropertyOp(JSObject *object)
72 return JS_DATA_TO_FUNC_PTR(PropertyOp, object);
75 static inline JSPropertyOp
76 CastAsJSPropertyOp(JSObject *object)
78 return JS_DATA_TO_FUNC_PTR(JSPropertyOp, object);
81 inline JSObject *
82 CastAsObject(PropertyOp op)
84 return JS_FUNC_TO_DATA_PTR(JSObject *, op);
87 inline Value
88 CastAsObjectJsval(PropertyOp op)
90 return ObjectOrNullValue(CastAsObject(op));
93 } /* namespace js */
96 * A representation of ECMA-262 ed. 5's internal property descriptor data
97 * structure.
99 struct PropDesc {
100 friend class js::AutoPropDescArrayRooter;
102 PropDesc();
104 public:
105 /* 8.10.5 ToPropertyDescriptor(Obj) */
106 bool initialize(JSContext* cx, jsid id, const js::Value &v);
108 /* 8.10.1 IsAccessorDescriptor(desc) */
109 bool isAccessorDescriptor() const {
110 return hasGet || hasSet;
113 /* 8.10.2 IsDataDescriptor(desc) */
114 bool isDataDescriptor() const {
115 return hasValue || hasWritable;
118 /* 8.10.3 IsGenericDescriptor(desc) */
119 bool isGenericDescriptor() const {
120 return !isAccessorDescriptor() && !isDataDescriptor();
123 bool configurable() const {
124 return (attrs & JSPROP_PERMANENT) == 0;
127 bool enumerable() const {
128 return (attrs & JSPROP_ENUMERATE) != 0;
131 bool writable() const {
132 return (attrs & JSPROP_READONLY) == 0;
135 JSObject* getterObject() const {
136 return get.isUndefined() ? NULL : &get.toObject();
138 JSObject* setterObject() const {
139 return set.isUndefined() ? NULL : &set.toObject();
142 const js::Value &getterValue() const {
143 return get;
145 const js::Value &setterValue() const {
146 return set;
149 js::PropertyOp getter() const {
150 return js::CastAsPropertyOp(getterObject());
152 js::PropertyOp setter() const {
153 return js::CastAsPropertyOp(setterObject());
156 js::Value pd;
157 jsid id;
158 js::Value value, get, set;
160 /* Property descriptor boolean fields. */
161 uint8 attrs;
163 /* Bits indicating which values are set. */
164 bool hasGet : 1;
165 bool hasSet : 1;
166 bool hasValue : 1;
167 bool hasWritable : 1;
168 bool hasEnumerable : 1;
169 bool hasConfigurable : 1;
172 namespace js {
174 typedef Vector<PropDesc, 1> PropDescArray;
176 } /* namespace js */
178 struct JSObjectMap {
179 uint32 shape; /* shape identifier */
180 uint32 slotSpan; /* one more than maximum live slot number */
182 static JS_FRIEND_DATA(const JSObjectMap) sharedNonNative;
184 explicit JSObjectMap(uint32 shape) : shape(shape), slotSpan(0) {}
185 JSObjectMap(uint32 shape, uint32 slotSpan) : shape(shape), slotSpan(slotSpan) {}
187 enum { INVALID_SHAPE = 0x8fffffff, SHAPELESS = 0xffffffff };
189 bool isNative() const { return this != &sharedNonNative; }
191 private:
192 /* No copy or assignment semantics. */
193 JSObjectMap(JSObjectMap &);
194 void operator=(JSObjectMap &);
198 * Unlike js_DefineNativeProperty, propp must be non-null. On success, and if
199 * id was found, return true with *objp non-null and with a property of *objp
200 * stored in *propp. If successful but id was not found, return true with both
201 * *objp and *propp null.
203 extern JS_FRIEND_API(JSBool)
204 js_LookupProperty(JSContext *cx, JSObject *obj, jsid id, JSObject **objp,
205 JSProperty **propp);
207 extern JSBool
208 js_DefineProperty(JSContext *cx, JSObject *obj, jsid id, const js::Value *value,
209 js::PropertyOp getter, js::PropertyOp setter, uintN attrs);
211 extern JSBool
212 js_GetProperty(JSContext *cx, JSObject *obj, JSObject *receiver, jsid id, js::Value *vp);
214 inline JSBool
215 js_GetProperty(JSContext *cx, JSObject *obj, jsid id, js::Value *vp)
217 return js_GetProperty(cx, obj, obj, id, vp);
220 namespace js {
222 extern JSBool
223 GetPropertyDefault(JSContext *cx, JSObject *obj, jsid id, const Value &def, Value *vp);
225 } /* namespace js */
227 extern JSBool
228 js_SetProperty(JSContext *cx, JSObject *obj, jsid id, js::Value *vp, JSBool strict);
230 extern JSBool
231 js_GetAttributes(JSContext *cx, JSObject *obj, jsid id, uintN *attrsp);
233 extern JSBool
234 js_SetAttributes(JSContext *cx, JSObject *obj, jsid id, uintN *attrsp);
236 extern JSBool
237 js_DeleteProperty(JSContext *cx, JSObject *obj, jsid id, js::Value *rval, JSBool strict);
239 extern JS_FRIEND_API(JSBool)
240 js_Enumerate(JSContext *cx, JSObject *obj, JSIterateOp enum_op,
241 js::Value *statep, jsid *idp);
243 extern JSType
244 js_TypeOf(JSContext *cx, JSObject *obj);
246 namespace js {
248 struct NativeIterator;
252 struct JSFunction;
254 namespace nanojit {
255 class ValidateWriter;
259 * JSObject struct, with members sized to fit in 32 bytes on 32-bit targets,
260 * 64 bytes on 64-bit systems. The JSFunction struct is an extension of this
261 * struct allocated from a larger GC size-class.
263 * The clasp member stores the js::Class pointer for this object. We do *not*
264 * synchronize updates of clasp or flags -- API clients must take care.
266 * An object is a delegate if it is on another object's prototype (the proto
267 * field) or scope chain (the parent field), and therefore the delegate might
268 * be asked implicitly to get or set a property on behalf of another object.
269 * Delegates may be accessed directly too, as may any object, but only those
270 * objects linked after the head of any prototype or scope chain are flagged
271 * as delegates. This definition helps to optimize shape-based property cache
272 * invalidation (see Purge{Scope,Proto}Chain in jsobj.cpp).
274 * The meaning of the system object bit is defined by the API client. It is
275 * set in JS_NewSystemObject and is queried by JS_IsSystemObject (jsdbgapi.h),
276 * but it has no intrinsic meaning to SpiderMonkey. Further, JSFILENAME_SYSTEM
277 * and JS_FlagScriptFilenamePrefix (also exported via jsdbgapi.h) are intended
278 * to be complementary to this bit, but it is up to the API client to implement
279 * any such association.
281 * Both these flag bits are initially zero; they may be set or queried using
282 * the (is|set)(Delegate|System) inline methods.
284 * The slots member is a pointer to the slot vector for the object.
285 * This can be either a fixed array allocated immediately after the object,
286 * or a dynamically allocated array. A dynamic array can be tested for with
287 * hasSlotsArray(). In all cases, capacity gives the number of usable slots.
288 * Two objects with the same shape have the same number of fixed slots,
289 * and either both have or neither have dynamically allocated slot arrays.
291 * If you change this struct, you'll probably need to change the AccSet values
292 * in jsbuiltins.h.
294 struct JSObject : js::gc::Cell {
296 * TraceRecorder must be a friend because it generates code that
297 * manipulates JSObjects, which requires peeking under any encapsulation.
298 * ValidateWriter must be a friend because it works in tandem with
299 * TraceRecorder.
301 friend class js::TraceRecorder;
302 friend class nanojit::ValidateWriter;
303 friend class GetPropCompiler;
306 * Private pointer to the last added property and methods to manipulate the
307 * list it links among properties in this scope. The {remove,insert} pair
308 * for DictionaryProperties assert that the scope is in dictionary mode and
309 * any reachable properties are flagged as dictionary properties.
311 * NB: these private methods do *not* update this scope's shape to track
312 * lastProp->shape after they finish updating the linked list in the case
313 * where lastProp is updated. It is up to calling code in jsscope.cpp to
314 * call updateShape(cx) after updating lastProp.
316 union {
317 js::Shape *lastProp;
318 JSObjectMap *map;
321 js::Class *clasp;
323 private:
324 inline void setLastProperty(const js::Shape *shape);
325 inline void removeLastProperty();
327 #ifdef DEBUG
328 void checkShapeConsistency();
329 #endif
331 public:
332 inline const js::Shape *lastProperty() const;
334 inline js::Shape **nativeSearch(jsid id, bool adding = false);
335 inline const js::Shape *nativeLookup(jsid id);
337 inline bool nativeContains(jsid id);
338 inline bool nativeContains(const js::Shape &shape);
340 enum {
341 DELEGATE = 0x01,
342 SYSTEM = 0x02,
343 NOT_EXTENSIBLE = 0x04,
344 BRANDED = 0x08,
345 GENERIC = 0x10,
346 METHOD_BARRIER = 0x20,
347 INDEXED = 0x40,
348 OWN_SHAPE = 0x80,
349 BOUND_FUNCTION = 0x100,
350 HAS_EQUALITY = 0x200,
351 METHOD_THRASH_COUNT_MASK = 0xc00,
352 METHOD_THRASH_COUNT_SHIFT = 10,
353 METHOD_THRASH_COUNT_MAX = METHOD_THRASH_COUNT_MASK >> METHOD_THRASH_COUNT_SHIFT
357 * Impose a sane upper bound, originally checked only for dense arrays, on
358 * number of slots in an object.
360 enum {
361 NSLOTS_BITS = 29,
362 NSLOTS_LIMIT = JS_BIT(NSLOTS_BITS)
365 uint32 flags; /* flags */
366 uint32 objShape; /* copy of lastProp->shape, or override if different */
368 /* If prototype, lazily filled array of empty shapes for each object size. */
369 js::EmptyShape **emptyShapes;
371 JSObject *proto; /* object's prototype */
372 JSObject *parent; /* object's parent */
373 void *privateData; /* private data */
374 jsuword capacity; /* capacity of slots */
375 js::Value *slots; /* dynamically allocated slots,
376 or pointer to fixedSlots() */
379 * Return an immutable, shareable, empty shape with the same clasp as this
380 * and the same slotSpan as this had when empty.
382 * If |this| is the scope of an object |proto|, the resulting scope can be
383 * used as the scope of a new object whose prototype is |proto|.
385 inline bool canProvideEmptyShape(js::Class *clasp);
386 inline js::EmptyShape *getEmptyShape(JSContext *cx, js::Class *aclasp,
387 /* gc::FinalizeKind */ unsigned kind);
389 bool isNative() const { return map->isNative(); }
391 js::Class *getClass() const { return clasp; }
392 JSClass *getJSClass() const { return Jsvalify(clasp); }
394 bool hasClass(const js::Class *c) const {
395 return c == clasp;
398 const js::ObjectOps *getOps() const {
399 return &getClass()->ops;
402 inline void trace(JSTracer *trc);
404 uint32 shape() const {
405 JS_ASSERT(objShape != JSObjectMap::INVALID_SHAPE);
406 return objShape;
409 bool isDelegate() const { return !!(flags & DELEGATE); }
410 void setDelegate() { flags |= DELEGATE; }
411 void clearDelegate() { flags &= ~DELEGATE; }
413 bool isBoundFunction() const { return !!(flags & BOUND_FUNCTION); }
415 static void setDelegateNullSafe(JSObject *obj) {
416 if (obj)
417 obj->setDelegate();
420 bool isSystem() const { return !!(flags & SYSTEM); }
421 void setSystem() { flags |= SYSTEM; }
424 * A branded object contains plain old methods (function-valued properties
425 * without magic getters and setters), and its shape evolves whenever a
426 * function value changes.
428 bool branded() { return !!(flags & BRANDED); }
431 * NB: these return false on shape overflow but do not report any error.
432 * Callers who depend on shape guarantees should therefore bail off trace,
433 * e.g., on false returns.
435 bool brand(JSContext *cx);
436 bool unbrand(JSContext *cx);
438 bool generic() { return !!(flags & GENERIC); }
439 void setGeneric() { flags |= GENERIC; }
441 uintN getMethodThrashCount() const {
442 return (flags & METHOD_THRASH_COUNT_MASK) >> METHOD_THRASH_COUNT_SHIFT;
445 void setMethodThrashCount(uintN count) {
446 JS_ASSERT(count <= METHOD_THRASH_COUNT_MAX);
447 flags = (flags & ~METHOD_THRASH_COUNT_MASK) | (count << METHOD_THRASH_COUNT_SHIFT);
450 bool hasSpecialEquality() const { return !!(flags & HAS_EQUALITY); }
451 void assertSpecialEqualitySynced() const {
452 JS_ASSERT(!!clasp->ext.equality == hasSpecialEquality());
455 /* Sets an object's HAS_EQUALITY flag based on its clasp. */
456 inline void syncSpecialEquality();
458 private:
459 void generateOwnShape(JSContext *cx);
461 void setOwnShape(uint32 s) { flags |= OWN_SHAPE; objShape = s; }
462 void clearOwnShape() { flags &= ~OWN_SHAPE; objShape = map->shape; }
464 public:
465 inline bool nativeEmpty() const;
467 bool hasOwnShape() const { return !!(flags & OWN_SHAPE); }
469 void setMap(const JSObjectMap *amap) {
470 JS_ASSERT(!hasOwnShape());
471 map = const_cast<JSObjectMap *>(amap);
472 objShape = map->shape;
475 void setSharedNonNativeMap() {
476 setMap(&JSObjectMap::sharedNonNative);
479 void deletingShapeChange(JSContext *cx, const js::Shape &shape);
480 bool methodShapeChange(JSContext *cx, const js::Shape &shape);
481 bool methodShapeChange(JSContext *cx, uint32 slot);
482 void protoShapeChange(JSContext *cx);
483 void shadowingShapeChange(JSContext *cx, const js::Shape &shape);
484 bool globalObjectOwnShapeChange(JSContext *cx);
486 void extensibleShapeChange(JSContext *cx) {
487 /* This will do for now. */
488 generateOwnShape(cx);
492 * A scope has a method barrier when some compiler-created "null closure"
493 * function objects (functions that do not use lexical bindings above their
494 * scope, only free variable names) that have a correct JSSLOT_PARENT value
495 * thanks to the COMPILE_N_GO optimization are stored as newly added direct
496 * property values of the scope's object.
498 * The de-facto standard JS language requires each evaluation of such a
499 * closure to result in a unique (according to === and observable effects)
500 * function object. ES3 tried to allow implementations to "join" such
501 * objects to a single compiler-created object, but this makes an overt
502 * mutation hazard, also an "identity hazard" against interoperation among
503 * implementations that join and do not join.
505 * To stay compatible with the de-facto standard, we store the compiler-
506 * created function object as the method value and set the METHOD_BARRIER
507 * flag.
509 * The method value is part of the method property tree node's identity, so
510 * it effectively brands the scope with a predictable shape corresponding
511 * to the method value, but without the overhead of setting the BRANDED
512 * flag, which requires assigning a new shape peculiar to each branded
513 * scope. Instead the shape is shared via the property tree among all the
514 * scopes referencing the method property tree node.
516 * Then when reading from a scope for which scope->hasMethodBarrier() is
517 * true, we count on the scope's qualified/guarded shape being unique and
518 * add a read barrier that clones the compiler-created function object on
519 * demand, reshaping the scope.
521 * This read barrier is bypassed when evaluating the callee sub-expression
522 * of a call expression (see the JOF_CALLOP opcodes in jsopcode.tbl), since
523 * such ops do not present an identity or mutation hazard. The compiler
524 * performs this optimization only for null closures that do not use their
525 * own name or equivalent built-in references (arguments.callee).
527 * The BRANDED write barrier, JSObject::methodWriteBarrer, must check for
528 * METHOD_BARRIER too, and regenerate this scope's shape if the method's
529 * value is in fact changing.
531 bool hasMethodBarrier() { return !!(flags & METHOD_BARRIER); }
532 void setMethodBarrier() { flags |= METHOD_BARRIER; }
535 * Test whether this object may be branded due to method calls, which means
536 * any assignment to a function-valued property must regenerate shape; else
537 * test whether this object has method properties, which require a method
538 * write barrier.
540 bool brandedOrHasMethodBarrier() { return !!(flags & (BRANDED | METHOD_BARRIER)); }
543 * Read barrier to clone a joined function object stored as a method.
544 * Defined in jsobjinlines.h, but not declared inline per standard style in
545 * order to avoid gcc warnings.
547 bool methodReadBarrier(JSContext *cx, const js::Shape &shape, js::Value *vp);
550 * Write barrier to check for a change of method value. Defined inline in
551 * jsobjinlines.h after methodReadBarrier. The slot flavor is required by
552 * JSOP_*GVAR, which deals in slots not shapes, while not deoptimizing to
553 * map slot to shape unless JSObject::flags show that this is necessary.
554 * The methodShapeChange overload (directly below) parallels this.
556 bool methodWriteBarrier(JSContext *cx, const js::Shape &shape, const js::Value &v);
557 bool methodWriteBarrier(JSContext *cx, uint32 slot, const js::Value &v);
559 bool isIndexed() const { return !!(flags & INDEXED); }
560 void setIndexed() { flags |= INDEXED; }
563 * Return true if this object is a native one that has been converted from
564 * shared-immutable prototype-rooted shape storage to dictionary-shapes in
565 * a doubly-linked list.
567 inline bool inDictionaryMode() const;
569 inline uint32 propertyCount() const;
571 inline bool hasPropertyTable() const;
573 /* gc::FinalizeKind */ unsigned finalizeKind() const;
575 uint32 numSlots() const { return capacity; }
577 size_t slotsAndStructSize(uint32 nslots) const;
578 size_t slotsAndStructSize() const { return slotsAndStructSize(numSlots()); }
580 inline js::Value* fixedSlots() const;
581 inline size_t numFixedSlots() const;
583 static inline size_t getFixedSlotOffset(size_t slot);
585 public:
586 /* Minimum size for dynamically allocated slots. */
587 static const uint32 SLOT_CAPACITY_MIN = 8;
589 bool allocSlots(JSContext *cx, size_t nslots);
590 bool growSlots(JSContext *cx, size_t nslots);
591 void shrinkSlots(JSContext *cx, size_t nslots);
593 bool ensureSlots(JSContext *cx, size_t nslots) {
594 if (numSlots() < nslots)
595 return growSlots(cx, nslots);
596 return true;
600 * Ensure that the object has at least JSCLASS_RESERVED_SLOTS(clasp) +
601 * nreserved slots.
603 * This method may be called only for native objects freshly created using
604 * NewObject or one of its variant where the new object will both (a) never
605 * escape to script and (b) never be extended with ad-hoc properties that
606 * would try to allocate higher slots without the fresh object first having
607 * its map set to a shape path that maps those slots.
609 * Block objects satisfy (a) and (b), as there is no evil eval-based way to
610 * add ad-hoc properties to a Block instance. Call objects satisfy (a) and
611 * (b) as well, because the compiler-created Shape path that covers args,
612 * vars, and upvars, stored in their callee function in u.i.names, becomes
613 * their initial map.
615 bool ensureInstanceReservedSlots(JSContext *cx, size_t nreserved);
618 * Get a direct pointer to the object's slots.
619 * This can be reallocated if the object is modified, watch out!
621 js::Value *getSlots() const {
622 return slots;
626 * NB: ensureClassReservedSlotsForEmptyObject asserts that nativeEmpty()
627 * Use ensureClassReservedSlots for any object, either empty or already
628 * extended with properties.
630 bool ensureClassReservedSlotsForEmptyObject(JSContext *cx);
632 inline bool ensureClassReservedSlots(JSContext *cx);
634 uint32 slotSpan() const { return map->slotSpan; }
636 bool containsSlot(uint32 slot) const { return slot < slotSpan(); }
638 js::Value& getSlotRef(uintN slot) {
639 JS_ASSERT(slot < capacity);
640 return slots[slot];
643 js::Value &nativeGetSlotRef(uintN slot) {
644 JS_ASSERT(isNative());
645 JS_ASSERT(containsSlot(slot));
646 return getSlotRef(slot);
649 const js::Value &getSlot(uintN slot) const {
650 JS_ASSERT(slot < capacity);
651 return slots[slot];
654 const js::Value &nativeGetSlot(uintN slot) const {
655 JS_ASSERT(isNative());
656 JS_ASSERT(containsSlot(slot));
657 return getSlot(slot);
660 void setSlot(uintN slot, const js::Value &value) {
661 JS_ASSERT(slot < capacity);
662 slots[slot] = value;
665 void nativeSetSlot(uintN slot, const js::Value &value) {
666 JS_ASSERT(isNative());
667 JS_ASSERT(containsSlot(slot));
668 return setSlot(slot, value);
671 inline js::Value getReservedSlot(uintN index) const;
673 /* Defined in jsscopeinlines.h to avoid including implementation dependencies here. */
674 inline void updateShape(JSContext *cx);
675 inline void updateFlags(const js::Shape *shape, bool isDefinitelyAtom = false);
677 /* Extend this object to have shape as its last-added property. */
678 inline void extend(JSContext *cx, const js::Shape *shape, bool isDefinitelyAtom = false);
680 JSObject *getProto() const { return proto; }
681 void clearProto() { proto = NULL; }
683 void setProto(JSObject *newProto) {
684 #ifdef DEBUG
685 for (JSObject *obj = newProto; obj; obj = obj->getProto())
686 JS_ASSERT(obj != this);
687 #endif
688 setDelegateNullSafe(newProto);
689 proto = newProto;
692 JSObject *getParent() const {
693 return parent;
696 void clearParent() {
697 parent = NULL;
700 void setParent(JSObject *newParent) {
701 #ifdef DEBUG
702 for (JSObject *obj = newParent; obj; obj = obj->getParent())
703 JS_ASSERT(obj != this);
704 #endif
705 setDelegateNullSafe(newParent);
706 parent = newParent;
709 JS_FRIEND_API(JSObject *) getGlobal() const;
711 bool isGlobal() const {
712 return !!(getClass()->flags & JSCLASS_IS_GLOBAL);
715 void *getPrivate() const {
716 JS_ASSERT(getClass()->flags & JSCLASS_HAS_PRIVATE);
717 return privateData;
720 void setPrivate(void *data) {
721 JS_ASSERT(getClass()->flags & JSCLASS_HAS_PRIVATE);
722 privateData = data;
727 * ES5 meta-object properties and operations.
730 private:
731 enum ImmutabilityType { SEAL, FREEZE };
734 * The guts of Object.seal (ES5 15.2.3.8) and Object.freeze (ES5 15.2.3.9): mark the
735 * object as non-extensible, and adjust each property's attributes appropriately: each
736 * property becomes non-configurable, and if |freeze|, data properties become
737 * read-only as well.
739 bool sealOrFreeze(JSContext *cx, ImmutabilityType it);
741 public:
742 bool isExtensible() const { return !(flags & NOT_EXTENSIBLE); }
743 bool preventExtensions(JSContext *cx, js::AutoIdVector *props);
745 /* ES5 15.2.3.8: non-extensible, all props non-configurable */
746 inline bool seal(JSContext *cx) { return sealOrFreeze(cx, SEAL); }
747 /* ES5 15.2.3.9: non-extensible, all properties non-configurable, all data props read-only */
748 bool freeze(JSContext *cx) { return sealOrFreeze(cx, FREEZE); }
751 * Primitive-specific getters and setters.
754 private:
755 static const uint32 JSSLOT_PRIMITIVE_THIS = 0;
757 public:
758 inline const js::Value &getPrimitiveThis() const;
759 inline void setPrimitiveThis(const js::Value &pthis);
762 * Array-specific getters and setters (for both dense and slow arrays).
765 inline uint32 getArrayLength() const;
766 inline void setArrayLength(uint32 length);
768 inline uint32 getDenseArrayCapacity();
769 inline js::Value* getDenseArrayElements();
770 inline const js::Value &getDenseArrayElement(uintN idx);
771 inline js::Value* addressOfDenseArrayElement(uintN idx);
772 inline void setDenseArrayElement(uintN idx, const js::Value &val);
773 inline void shrinkDenseArrayElements(JSContext *cx, uintN cap);
776 * ensureDenseArrayElements ensures that the dense array can hold at least
777 * index + extra elements. It returns ED_OK on success, ED_FAILED on
778 * failure to grow the array, ED_SPARSE when the array is too sparse to
779 * grow (this includes the case of index + extra overflow). In the last
780 * two cases the array is kept intact.
782 enum EnsureDenseResult { ED_OK, ED_FAILED, ED_SPARSE };
783 inline EnsureDenseResult ensureDenseArrayElements(JSContext *cx, uintN index, uintN extra);
786 * Check if after growing the dense array will be too sparse.
787 * newElementsHint is an estimated number of elements to be added.
789 bool willBeSparseDenseArray(uintN requiredCapacity, uintN newElementsHint);
791 JSBool makeDenseArraySlow(JSContext *cx);
794 * Arguments-specific getters and setters.
797 private:
799 * We represent arguments objects using js_ArgumentsClass and
800 * js::StrictArgumentsClass. The two are structured similarly, and methods
801 * valid on arguments objects of one class are also generally valid on
802 * arguments objects of the other.
804 * Arguments objects of either class store arguments length in a slot:
806 * JSSLOT_ARGS_LENGTH - the number of actual arguments and a flag
807 * indicating whether arguments.length was
808 * overwritten. This slot is not used to represent
809 * arguments.length after that property has been
810 * assigned, even if the new value is integral: it's
811 * always the original length.
813 * Both arguments classes use a slot for storing arguments data:
815 * JSSLOT_ARGS_DATA - pointer to an ArgumentsData structure
817 * ArgumentsData for normal arguments stores the value of arguments.callee,
818 * as long as that property has not been overwritten. If arguments.callee
819 * is overwritten, the corresponding value in ArgumentsData is set to
820 * MagicValue(JS_ARGS_HOLE). Strict arguments do not store this value
821 * because arguments.callee is a poison pill for strict mode arguments.
823 * The ArgumentsData structure also stores argument values. For normal
824 * arguments this occurs after the corresponding function has returned, and
825 * for strict arguments this occurs when the arguments object is created,
826 * or sometimes shortly after (but not observably so). arguments[i] is
827 * stored in ArgumentsData.slots[i], accessible via getArgsElement() and
828 * setArgsElement(). Deletion of arguments[i] overwrites that slot with
829 * MagicValue(JS_ARGS_HOLE); subsequent redefinition of arguments[i] will
830 * use a normal property to store the value, ignoring the slot.
832 * Non-strict arguments have a private:
834 * private - the function's stack frame until the function
835 * returns, when it is replaced with null; also,
836 * JS_ARGUMENTS_OBJECT_ON_TRACE while on trace, if
837 * arguments was created on trace
839 * Technically strict arguments have a private, but it's always null.
840 * Conceptually it would be better to remove this oddity, but preserving it
841 * allows us to work with arguments objects of either kind more abstractly,
842 * so we keep it for now.
844 static const uint32 JSSLOT_ARGS_DATA = 1;
846 public:
847 /* Number of extra fixed arguments object slots besides JSSLOT_PRIVATE. */
848 static const uint32 JSSLOT_ARGS_LENGTH = 0;
849 static const uint32 ARGS_CLASS_RESERVED_SLOTS = 2;
850 static const uint32 ARGS_FIRST_FREE_SLOT = ARGS_CLASS_RESERVED_SLOTS + 1;
852 /* Lower-order bit stolen from the length slot. */
853 static const uint32 ARGS_LENGTH_OVERRIDDEN_BIT = 0x1;
854 static const uint32 ARGS_PACKED_BITS_COUNT = 1;
857 * Set the initial length of the arguments, and mark it as not overridden.
859 inline void setArgsLength(uint32 argc);
862 * Return the initial length of the arguments. This may differ from the
863 * current value of arguments.length!
865 inline uint32 getArgsInitialLength() const;
867 inline void setArgsLengthOverridden();
868 inline bool isArgsLengthOverridden() const;
870 inline js::ArgumentsData *getArgsData() const;
871 inline void setArgsData(js::ArgumentsData *data);
873 inline const js::Value &getArgsCallee() const;
874 inline void setArgsCallee(const js::Value &callee);
876 inline const js::Value &getArgsElement(uint32 i) const;
877 inline js::Value *getArgsElements() const;
878 inline js::Value *addressOfArgsElement(uint32 i);
879 inline void setArgsElement(uint32 i, const js::Value &v);
881 private:
883 * Reserved slot structure for Call objects:
885 * private - the stack frame corresponding to the Call object
886 * until js_PutCallObject or its on-trace analog
887 * is called, null thereafter
888 * JSSLOT_CALL_CALLEE - callee function for the stack frame, or null if
889 * the stack frame is for strict mode eval code
890 * JSSLOT_CALL_ARGUMENTS - arguments object for non-strict mode eval stack
891 * frames (not valid for strict mode eval frames)
893 static const uint32 JSSLOT_CALL_CALLEE = 0;
894 static const uint32 JSSLOT_CALL_ARGUMENTS = 1;
896 public:
897 /* Number of reserved slots. */
898 static const uint32 CALL_RESERVED_SLOTS = 2;
900 /* True if this is for a strict mode eval frame or for a function call. */
901 inline bool callIsForEval() const;
903 /* The stack frame for this Call object, if the frame is still active. */
904 inline JSStackFrame *maybeCallObjStackFrame() const;
907 * The callee function if this Call object was created for a function
908 * invocation, or null if it was created for a strict mode eval frame.
910 inline JSObject *getCallObjCallee() const;
911 inline JSFunction *getCallObjCalleeFunction() const;
912 inline void setCallObjCallee(JSObject *callee);
914 inline const js::Value &getCallObjArguments() const;
915 inline void setCallObjArguments(const js::Value &v);
917 /* Returns the formal argument at the given index. */
918 inline const js::Value &callObjArg(uintN i) const;
919 inline js::Value &callObjArg(uintN i);
921 /* Returns the variable at the given index. */
922 inline const js::Value &callObjVar(uintN i) const;
923 inline js::Value &callObjVar(uintN i);
926 * Date-specific getters and setters.
929 static const uint32 JSSLOT_DATE_UTC_TIME = 0;
932 * Cached slots holding local properties of the date.
933 * These are undefined until the first actual lookup occurs
934 * and are reset to undefined whenever the date's time is modified.
936 static const uint32 JSSLOT_DATE_COMPONENTS_START = 1;
938 static const uint32 JSSLOT_DATE_LOCAL_TIME = 1;
939 static const uint32 JSSLOT_DATE_LOCAL_YEAR = 2;
940 static const uint32 JSSLOT_DATE_LOCAL_MONTH = 3;
941 static const uint32 JSSLOT_DATE_LOCAL_DATE = 4;
942 static const uint32 JSSLOT_DATE_LOCAL_DAY = 5;
943 static const uint32 JSSLOT_DATE_LOCAL_HOURS = 6;
944 static const uint32 JSSLOT_DATE_LOCAL_MINUTES = 7;
945 static const uint32 JSSLOT_DATE_LOCAL_SECONDS = 8;
947 static const uint32 DATE_CLASS_RESERVED_SLOTS = 9;
949 inline const js::Value &getDateUTCTime() const;
950 inline void setDateUTCTime(const js::Value &pthis);
953 * Function-specific getters and setters.
956 private:
957 friend struct JSFunction;
958 friend class js::mjit::Compiler;
961 * Flat closures with one or more upvars snapshot the upvars' values into a
962 * vector of js::Values referenced from this slot.
964 static const uint32 JSSLOT_FLAT_CLOSURE_UPVARS = 0;
967 * Null closures set or initialized as methods have these slots. See the
968 * "method barrier" comments and methods.
971 static const uint32 JSSLOT_FUN_METHOD_ATOM = 0;
972 static const uint32 JSSLOT_FUN_METHOD_OBJ = 1;
974 static const uint32 JSSLOT_BOUND_FUNCTION_THIS = 0;
975 static const uint32 JSSLOT_BOUND_FUNCTION_ARGS_COUNT = 1;
977 public:
978 static const uint32 FUN_CLASS_RESERVED_SLOTS = 2;
980 inline JSFunction *getFunctionPrivate() const;
982 inline js::Value *getFlatClosureUpvars() const;
983 inline js::Value getFlatClosureUpvar(uint32 i) const;
984 inline js::Value &getFlatClosureUpvar(uint32 i);
985 inline void setFlatClosureUpvars(js::Value *upvars);
987 inline bool hasMethodObj(const JSObject& obj) const;
988 inline void setMethodObj(JSObject& obj);
990 inline bool initBoundFunction(JSContext *cx, const js::Value &thisArg,
991 const js::Value *args, uintN argslen);
993 inline JSObject *getBoundFunctionTarget() const;
994 inline const js::Value &getBoundFunctionThis() const;
995 inline const js::Value *getBoundFunctionArguments(uintN &argslen) const;
998 * RegExp-specific getters and setters.
1001 private:
1002 static const uint32 JSSLOT_REGEXP_LAST_INDEX = 0;
1004 public:
1005 static const uint32 REGEXP_CLASS_RESERVED_SLOTS = 1;
1007 inline const js::Value &getRegExpLastIndex() const;
1008 inline void setRegExpLastIndex(const js::Value &v);
1009 inline void setRegExpLastIndex(jsdouble d);
1010 inline void zeroRegExpLastIndex();
1013 * Iterator-specific getters and setters.
1016 inline js::NativeIterator *getNativeIterator() const;
1017 inline void setNativeIterator(js::NativeIterator *);
1020 * XML-related getters and setters.
1024 * Slots for XML-related classes are as follows:
1025 * - js_NamespaceClass.base reserves the *_NAME_* and *_NAMESPACE_* slots.
1026 * - js_QNameClass.base, js_AttributeNameClass, js_AnyNameClass reserve
1027 * the *_NAME_* and *_QNAME_* slots.
1028 * - Others (js_XMLClass, js_XMLFilterClass) don't reserve any slots.
1030 private:
1031 static const uint32 JSSLOT_NAME_PREFIX = 0; // shared
1032 static const uint32 JSSLOT_NAME_URI = 1; // shared
1034 static const uint32 JSSLOT_NAMESPACE_DECLARED = 2;
1036 static const uint32 JSSLOT_QNAME_LOCAL_NAME = 2;
1038 public:
1039 static const uint32 NAMESPACE_CLASS_RESERVED_SLOTS = 3;
1040 static const uint32 QNAME_CLASS_RESERVED_SLOTS = 3;
1042 inline JSLinearString *getNamePrefix() const;
1043 inline jsval getNamePrefixVal() const;
1044 inline void setNamePrefix(JSLinearString *prefix);
1045 inline void clearNamePrefix();
1047 inline JSLinearString *getNameURI() const;
1048 inline jsval getNameURIVal() const;
1049 inline void setNameURI(JSLinearString *uri);
1051 inline jsval getNamespaceDeclared() const;
1052 inline void setNamespaceDeclared(jsval decl);
1054 inline JSLinearString *getQNameLocalName() const;
1055 inline jsval getQNameLocalNameVal() const;
1056 inline void setQNameLocalName(JSLinearString *name);
1059 * Proxy-specific getters and setters.
1062 inline js::JSProxyHandler *getProxyHandler() const;
1063 inline const js::Value &getProxyPrivate() const;
1064 inline void setProxyPrivate(const js::Value &priv);
1065 inline const js::Value &getProxyExtra() const;
1066 inline void setProxyExtra(const js::Value &extra);
1069 * With object-specific getters and setters.
1071 inline JSObject *getWithThis() const;
1072 inline void setWithThis(JSObject *thisp);
1075 * Back to generic stuff.
1077 inline bool isCallable();
1079 /* The map field is not initialized here and should be set separately. */
1080 void init(JSContext *cx, js::Class *aclasp, JSObject *proto, JSObject *parent,
1081 void *priv, bool useHoles);
1083 inline void finish(JSContext *cx);
1084 JS_ALWAYS_INLINE void finalize(JSContext *cx);
1087 * Like init, but also initializes map. The catch: proto must be the result
1088 * of a call to js_InitClass(...clasp, ...).
1090 inline bool initSharingEmptyShape(JSContext *cx,
1091 js::Class *clasp,
1092 JSObject *proto,
1093 JSObject *parent,
1094 void *priv,
1095 /* gc::FinalizeKind */ unsigned kind);
1097 inline bool hasSlotsArray() const;
1099 /* This method can only be called when hasSlotsArray() returns true. */
1100 inline void freeSlotsArray(JSContext *cx);
1102 /* Free the slots array and copy slots that fit into the fixed array. */
1103 inline void revertToFixedSlots(JSContext *cx);
1105 inline bool hasProperty(JSContext *cx, jsid id, bool *foundp, uintN flags = 0);
1108 * Allocate and free an object slot. Note that freeSlot is infallible: it
1109 * returns true iff this is a dictionary-mode object and the freed slot was
1110 * added to the freelist.
1112 * FIXME: bug 593129 -- slot allocation should be done by object methods
1113 * after calling object-parameter-free shape methods, avoiding coupling
1114 * logic across the object vs. shape module wall.
1116 bool allocSlot(JSContext *cx, uint32 *slotp);
1117 bool freeSlot(JSContext *cx, uint32 slot);
1119 bool reportReadOnly(JSContext* cx, jsid id, uintN report = JSREPORT_ERROR);
1120 bool reportNotConfigurable(JSContext* cx, jsid id, uintN report = JSREPORT_ERROR);
1121 bool reportNotExtensible(JSContext *cx, uintN report = JSREPORT_ERROR);
1123 private:
1124 js::Shape *getChildProperty(JSContext *cx, js::Shape *parent, js::Shape &child);
1127 * Internal helper that adds a shape not yet mapped by this object.
1129 * Notes:
1130 * 1. getter and setter must be normalized based on flags (see jsscope.cpp).
1131 * 2. !isExtensible() checking must be done by callers.
1133 const js::Shape *addPropertyInternal(JSContext *cx, jsid id,
1134 js::PropertyOp getter, js::PropertyOp setter,
1135 uint32 slot, uintN attrs,
1136 uintN flags, intN shortid,
1137 js::Shape **spp);
1139 bool toDictionaryMode(JSContext *cx);
1141 public:
1142 /* Add a property whose id is not yet in this scope. */
1143 const js::Shape *addProperty(JSContext *cx, jsid id,
1144 js::PropertyOp getter, js::PropertyOp setter,
1145 uint32 slot, uintN attrs,
1146 uintN flags, intN shortid);
1148 /* Add a data property whose id is not yet in this scope. */
1149 const js::Shape *addDataProperty(JSContext *cx, jsid id, uint32 slot, uintN attrs) {
1150 JS_ASSERT(!(attrs & (JSPROP_GETTER | JSPROP_SETTER)));
1151 return addProperty(cx, id, NULL, NULL, slot, attrs, 0, 0);
1154 /* Add or overwrite a property for id in this scope. */
1155 const js::Shape *putProperty(JSContext *cx, jsid id,
1156 js::PropertyOp getter, js::PropertyOp setter,
1157 uint32 slot, uintN attrs,
1158 uintN flags, intN shortid);
1160 /* Change the given property into a sibling with the same id in this scope. */
1161 const js::Shape *changeProperty(JSContext *cx, const js::Shape *shape, uintN attrs, uintN mask,
1162 js::PropertyOp getter, js::PropertyOp setter);
1164 /* Remove the property named by id from this object. */
1165 bool removeProperty(JSContext *cx, jsid id);
1167 /* Clear the scope, making it empty. */
1168 void clear(JSContext *cx);
1170 JSBool lookupProperty(JSContext *cx, jsid id, JSObject **objp, JSProperty **propp) {
1171 js::LookupPropOp op = getOps()->lookupProperty;
1172 return (op ? op : js_LookupProperty)(cx, this, id, objp, propp);
1175 JSBool defineProperty(JSContext *cx, jsid id, const js::Value &value,
1176 js::PropertyOp getter = js::PropertyStub,
1177 js::PropertyOp setter = js::PropertyStub,
1178 uintN attrs = JSPROP_ENUMERATE) {
1179 js::DefinePropOp op = getOps()->defineProperty;
1180 return (op ? op : js_DefineProperty)(cx, this, id, &value, getter, setter, attrs);
1183 JSBool getProperty(JSContext *cx, JSObject *receiver, jsid id, js::Value *vp) {
1184 js::PropertyIdOp op = getOps()->getProperty;
1185 return (op ? op : (js::PropertyIdOp)js_GetProperty)(cx, this, receiver, id, vp);
1188 JSBool getProperty(JSContext *cx, jsid id, js::Value *vp) {
1189 return getProperty(cx, this, id, vp);
1192 JSBool setProperty(JSContext *cx, jsid id, js::Value *vp, JSBool strict) {
1193 js::StrictPropertyIdOp op = getOps()->setProperty;
1194 return (op ? op : js_SetProperty)(cx, this, id, vp, strict);
1197 JSBool getAttributes(JSContext *cx, jsid id, uintN *attrsp) {
1198 js::AttributesOp op = getOps()->getAttributes;
1199 return (op ? op : js_GetAttributes)(cx, this, id, attrsp);
1202 JSBool setAttributes(JSContext *cx, jsid id, uintN *attrsp) {
1203 js::AttributesOp op = getOps()->setAttributes;
1204 return (op ? op : js_SetAttributes)(cx, this, id, attrsp);
1207 JSBool deleteProperty(JSContext *cx, jsid id, js::Value *rval, JSBool strict) {
1208 js::DeleteIdOp op = getOps()->deleteProperty;
1209 return (op ? op : js_DeleteProperty)(cx, this, id, rval, strict);
1212 JSBool enumerate(JSContext *cx, JSIterateOp iterop, js::Value *statep, jsid *idp) {
1213 js::NewEnumerateOp op = getOps()->enumerate;
1214 return (op ? op : js_Enumerate)(cx, this, iterop, statep, idp);
1217 JSType typeOf(JSContext *cx) {
1218 js::TypeOfOp op = getOps()->typeOf;
1219 return (op ? op : js_TypeOf)(cx, this);
1222 /* These four are time-optimized to avoid stub calls. */
1223 JSObject *thisObject(JSContext *cx) {
1224 JSObjectOp op = getOps()->thisObject;
1225 return op ? op(cx, this) : this;
1228 static bool thisObject(JSContext *cx, const js::Value &v, js::Value *vp);
1230 inline JSCompartment *getCompartment() const;
1232 inline JSObject *getThrowTypeError() const;
1234 JS_FRIEND_API(JSObject *) clone(JSContext *cx, JSObject *proto, JSObject *parent);
1235 JS_FRIEND_API(bool) copyPropertiesFrom(JSContext *cx, JSObject *obj);
1236 bool swap(JSContext *cx, JSObject *other);
1238 const js::Shape *defineBlockVariable(JSContext *cx, jsid id, intN index);
1240 inline bool canHaveMethodBarrier() const;
1242 inline bool isArguments() const;
1243 inline bool isNormalArguments() const;
1244 inline bool isStrictArguments() const;
1245 inline bool isArray() const;
1246 inline bool isDenseArray() const;
1247 inline bool isSlowArray() const;
1248 inline bool isNumber() const;
1249 inline bool isBoolean() const;
1250 inline bool isString() const;
1251 inline bool isPrimitive() const;
1252 inline bool isDate() const;
1253 inline bool isFunction() const;
1254 inline bool isObject() const;
1255 inline bool isWith() const;
1256 inline bool isBlock() const;
1257 inline bool isStaticBlock() const;
1258 inline bool isClonedBlock() const;
1259 inline bool isCall() const;
1260 inline bool isRegExp() const;
1261 inline bool isXML() const;
1262 inline bool isXMLId() const;
1263 inline bool isNamespace() const;
1264 inline bool isQName() const;
1266 inline bool isProxy() const;
1267 inline bool isObjectProxy() const;
1268 inline bool isFunctionProxy() const;
1270 JS_FRIEND_API(bool) isWrapper() const;
1271 JS_FRIEND_API(JSObject *) unwrap(uintN *flagsp = NULL);
1273 inline void initArrayClass();
1276 /* Check alignment for any fixed slots allocated after the object. */
1277 JS_STATIC_ASSERT(sizeof(JSObject) % sizeof(js::Value) == 0);
1279 inline js::Value*
1280 JSObject::fixedSlots() const {
1281 return (js::Value*) (jsuword(this) + sizeof(JSObject));
1284 inline bool
1285 JSObject::hasSlotsArray() const { return this->slots != fixedSlots(); }
1287 /* static */ inline size_t
1288 JSObject::getFixedSlotOffset(size_t slot) {
1289 return sizeof(JSObject) + (slot * sizeof(js::Value));
1292 struct JSObject_Slots2 : JSObject { js::Value fslots[2]; };
1293 struct JSObject_Slots4 : JSObject { js::Value fslots[4]; };
1294 struct JSObject_Slots8 : JSObject { js::Value fslots[8]; };
1295 struct JSObject_Slots12 : JSObject { js::Value fslots[12]; };
1296 struct JSObject_Slots16 : JSObject { js::Value fslots[16]; };
1298 #define JSSLOT_FREE(clasp) JSCLASS_RESERVED_SLOTS(clasp)
1300 #ifdef JS_THREADSAFE
1303 * The GC runs only when all threads except the one on which the GC is active
1304 * are suspended at GC-safe points, so calling obj->getSlot() from the GC's
1305 * thread is safe when rt->gcRunning is set. See jsgc.cpp for details.
1307 #define THREAD_IS_RUNNING_GC(rt, thread) \
1308 ((rt)->gcRunning && (rt)->gcThread == (thread))
1310 #define CX_THREAD_IS_RUNNING_GC(cx) \
1311 THREAD_IS_RUNNING_GC((cx)->runtime, (cx)->thread)
1313 #endif /* JS_THREADSAFE */
1315 inline void
1316 OBJ_TO_INNER_OBJECT(JSContext *cx, JSObject *&obj)
1318 if (JSObjectOp op = obj->getClass()->ext.innerObject)
1319 obj = op(cx, obj);
1322 inline void
1323 OBJ_TO_OUTER_OBJECT(JSContext *cx, JSObject *&obj)
1325 if (JSObjectOp op = obj->getClass()->ext.outerObject)
1326 obj = op(cx, obj);
1329 class JSValueArray {
1330 public:
1331 jsval *array;
1332 size_t length;
1334 JSValueArray(jsval *v, size_t c) : array(v), length(c) {}
1337 class ValueArray {
1338 public:
1339 js::Value *array;
1340 size_t length;
1342 ValueArray(js::Value *v, size_t c) : array(v), length(c) {}
1345 extern js::Class js_ObjectClass;
1346 extern js::Class js_WithClass;
1347 extern js::Class js_BlockClass;
1349 inline bool JSObject::isObject() const { return getClass() == &js_ObjectClass; }
1350 inline bool JSObject::isWith() const { return getClass() == &js_WithClass; }
1351 inline bool JSObject::isBlock() const { return getClass() == &js_BlockClass; }
1354 * Block scope object macros. The slots reserved by js_BlockClass are:
1356 * private JSStackFrame * active frame pointer or null
1357 * JSSLOT_BLOCK_DEPTH int depth of block slots in frame
1359 * After JSSLOT_BLOCK_DEPTH come one or more slots for the block locals.
1361 * A With object is like a Block object, in that both have one reserved slot
1362 * telling the stack depth of the relevant slots (the slot whose value is the
1363 * object named in the with statement, the slots containing the block's local
1364 * variables); and both have a private slot referring to the JSStackFrame in
1365 * whose activation they were created (or null if the with or block object
1366 * outlives the frame).
1368 static const uint32 JSSLOT_BLOCK_DEPTH = 0;
1369 static const uint32 JSSLOT_BLOCK_FIRST_FREE_SLOT = JSSLOT_BLOCK_DEPTH + 1;
1371 inline bool
1372 JSObject::isStaticBlock() const
1374 return isBlock() && !getProto();
1377 inline bool
1378 JSObject::isClonedBlock() const
1380 return isBlock() && !!getProto();
1383 static const uint32 JSSLOT_WITH_THIS = 1;
1385 #define OBJ_BLOCK_COUNT(cx,obj) \
1386 (obj)->propertyCount()
1387 #define OBJ_BLOCK_DEPTH(cx,obj) \
1388 (obj)->getSlot(JSSLOT_BLOCK_DEPTH).toInt32()
1389 #define OBJ_SET_BLOCK_DEPTH(cx,obj,depth) \
1390 (obj)->setSlot(JSSLOT_BLOCK_DEPTH, Value(Int32Value(depth)))
1393 * To make sure this slot is well-defined, always call js_NewWithObject to
1394 * create a With object, don't call js_NewObject directly. When creating a
1395 * With object that does not correspond to a stack slot, pass -1 for depth.
1397 * When popping the stack across this object's "with" statement, client code
1398 * must call withobj->setPrivate(NULL).
1400 extern JS_REQUIRES_STACK JSObject *
1401 js_NewWithObject(JSContext *cx, JSObject *proto, JSObject *parent, jsint depth);
1403 inline JSObject *
1404 js_UnwrapWithObject(JSContext *cx, JSObject *withobj)
1406 JS_ASSERT(withobj->getClass() == &js_WithClass);
1407 return withobj->getProto();
1411 * Create a new block scope object not linked to any proto or parent object.
1412 * Blocks are created by the compiler to reify let blocks and comprehensions.
1413 * Only when dynamic scope is captured do they need to be cloned and spliced
1414 * into an active scope chain.
1416 extern JSObject *
1417 js_NewBlockObject(JSContext *cx);
1419 extern JSObject *
1420 js_CloneBlockObject(JSContext *cx, JSObject *proto, JSStackFrame *fp);
1422 extern JS_REQUIRES_STACK JSBool
1423 js_PutBlockObject(JSContext *cx, JSBool normalUnwind);
1425 JSBool
1426 js_XDRBlockObject(JSXDRState *xdr, JSObject **objp);
1428 struct JSSharpObjectMap {
1429 jsrefcount depth;
1430 jsatomid sharpgen;
1431 JSHashTable *table;
1434 #define SHARP_BIT ((jsatomid) 1)
1435 #define BUSY_BIT ((jsatomid) 2)
1436 #define SHARP_ID_SHIFT 2
1437 #define IS_SHARP(he) (uintptr_t((he)->value) & SHARP_BIT)
1438 #define MAKE_SHARP(he) ((he)->value = (void *) (uintptr_t((he)->value)|SHARP_BIT))
1439 #define IS_BUSY(he) (uintptr_t((he)->value) & BUSY_BIT)
1440 #define MAKE_BUSY(he) ((he)->value = (void *) (uintptr_t((he)->value)|BUSY_BIT))
1441 #define CLEAR_BUSY(he) ((he)->value = (void *) (uintptr_t((he)->value)&~BUSY_BIT))
1443 extern JSHashEntry *
1444 js_EnterSharpObject(JSContext *cx, JSObject *obj, JSIdArray **idap,
1445 jschar **sp);
1447 extern void
1448 js_LeaveSharpObject(JSContext *cx, JSIdArray **idap);
1451 * Mark objects stored in map if GC happens between js_EnterSharpObject
1452 * and js_LeaveSharpObject. GC calls this when map->depth > 0.
1454 extern void
1455 js_TraceSharpMap(JSTracer *trc, JSSharpObjectMap *map);
1457 extern JSBool
1458 js_HasOwnPropertyHelper(JSContext *cx, js::LookupPropOp lookup, uintN argc,
1459 js::Value *vp);
1461 extern JSBool
1462 js_HasOwnProperty(JSContext *cx, js::LookupPropOp lookup, JSObject *obj, jsid id,
1463 JSObject **objp, JSProperty **propp);
1465 extern JSBool
1466 js_NewPropertyDescriptorObject(JSContext *cx, jsid id, uintN attrs,
1467 const js::Value &getter, const js::Value &setter,
1468 const js::Value &value, js::Value *vp);
1470 extern JSBool
1471 js_PropertyIsEnumerable(JSContext *cx, JSObject *obj, jsid id, js::Value *vp);
1473 #ifdef OLD_GETTER_SETTER_METHODS
1474 JS_FRIEND_API(JSBool) js_obj_defineGetter(JSContext *cx, uintN argc, js::Value *vp);
1475 JS_FRIEND_API(JSBool) js_obj_defineSetter(JSContext *cx, uintN argc, js::Value *vp);
1476 #endif
1478 extern JSObject *
1479 js_InitObjectClass(JSContext *cx, JSObject *obj);
1481 extern JSObject *
1482 js_InitClass(JSContext *cx, JSObject *obj, JSObject *parent_proto,
1483 js::Class *clasp, js::Native constructor, uintN nargs,
1484 JSPropertySpec *ps, JSFunctionSpec *fs,
1485 JSPropertySpec *static_ps, JSFunctionSpec *static_fs);
1488 * Select Object.prototype method names shared between jsapi.cpp and jsobj.cpp.
1490 extern const char js_watch_str[];
1491 extern const char js_unwatch_str[];
1492 extern const char js_hasOwnProperty_str[];
1493 extern const char js_isPrototypeOf_str[];
1494 extern const char js_propertyIsEnumerable_str[];
1496 #ifdef OLD_GETTER_SETTER_METHODS
1497 extern const char js_defineGetter_str[];
1498 extern const char js_defineSetter_str[];
1499 extern const char js_lookupGetter_str[];
1500 extern const char js_lookupSetter_str[];
1501 #endif
1503 extern JSBool
1504 js_PopulateObject(JSContext *cx, JSObject *newborn, JSObject *props);
1507 * Fast access to immutable standard objects (constructors and prototypes).
1509 extern JSBool
1510 js_GetClassObject(JSContext *cx, JSObject *obj, JSProtoKey key,
1511 JSObject **objp);
1513 extern JSBool
1514 js_SetClassObject(JSContext *cx, JSObject *obj, JSProtoKey key,
1515 JSObject *cobj, JSObject *prototype);
1518 * If protoKey is not JSProto_Null, then clasp is ignored. If protoKey is
1519 * JSProto_Null, clasp must non-null.
1521 extern JSBool
1522 js_FindClassObject(JSContext *cx, JSObject *start, JSProtoKey key,
1523 js::Value *vp, js::Class *clasp = NULL);
1525 extern JSObject *
1526 js_ConstructObject(JSContext *cx, js::Class *clasp, JSObject *proto,
1527 JSObject *parent, uintN argc, js::Value *argv);
1529 // Specialized call for constructing |this| with a known function callee,
1530 // and a known prototype.
1531 extern JSObject *
1532 js_CreateThisForFunctionWithProto(JSContext *cx, JSObject *callee, JSObject *proto);
1534 // Specialized call for constructing |this| with a known function callee.
1535 extern JSObject *
1536 js_CreateThisForFunction(JSContext *cx, JSObject *callee);
1538 // Generic call for constructing |this|.
1539 extern JSObject *
1540 js_CreateThis(JSContext *cx, JSObject *callee);
1542 extern jsid
1543 js_CheckForStringIndex(jsid id);
1546 * js_PurgeScopeChain does nothing if obj is not itself a prototype or parent
1547 * scope, else it reshapes the scope and prototype chains it links. It calls
1548 * js_PurgeScopeChainHelper, which asserts that obj is flagged as a delegate
1549 * (i.e., obj has ever been on a prototype or parent chain).
1551 extern void
1552 js_PurgeScopeChainHelper(JSContext *cx, JSObject *obj, jsid id);
1554 inline void
1555 js_PurgeScopeChain(JSContext *cx, JSObject *obj, jsid id)
1557 if (obj->isDelegate())
1558 js_PurgeScopeChainHelper(cx, obj, id);
1562 * Find or create a property named by id in obj's scope, with the given getter
1563 * and setter, slot, attributes, and other members.
1565 extern const js::Shape *
1566 js_AddNativeProperty(JSContext *cx, JSObject *obj, jsid id,
1567 js::PropertyOp getter, js::PropertyOp setter, uint32 slot,
1568 uintN attrs, uintN flags, intN shortid);
1571 * Change shape to have the given attrs, getter, and setter in scope, morphing
1572 * it into a potentially new js::Shape. Return a pointer to the changed
1573 * or identical property.
1575 extern const js::Shape *
1576 js_ChangeNativePropertyAttrs(JSContext *cx, JSObject *obj,
1577 const js::Shape *shape, uintN attrs, uintN mask,
1578 js::PropertyOp getter, js::PropertyOp setter);
1580 extern JSBool
1581 js_DefineOwnProperty(JSContext *cx, JSObject *obj, jsid id,
1582 const js::Value &descriptor, JSBool *bp);
1585 * Flags for the defineHow parameter of js_DefineNativeProperty.
1587 const uintN JSDNP_CACHE_RESULT = 1; /* an interpreter call from JSOP_INITPROP */
1588 const uintN JSDNP_DONT_PURGE = 2; /* suppress js_PurgeScopeChain */
1589 const uintN JSDNP_SET_METHOD = 4; /* js_{DefineNativeProperty,SetPropertyHelper}
1590 must pass the js::Shape::METHOD
1591 flag on to JSObject::{add,put}Property */
1592 const uintN JSDNP_UNQUALIFIED = 8; /* Unqualified property set. Only used in
1593 the defineHow argument of
1594 js_SetPropertyHelper. */
1597 * On error, return false. On success, if propp is non-null, return true with
1598 * obj locked and with a held property in *propp; if propp is null, return true
1599 * but release obj's lock first.
1601 extern JSBool
1602 js_DefineNativeProperty(JSContext *cx, JSObject *obj, jsid id, const js::Value &value,
1603 js::PropertyOp getter, js::PropertyOp setter, uintN attrs,
1604 uintN flags, intN shortid, JSProperty **propp,
1605 uintN defineHow = 0);
1608 * Specialized subroutine that allows caller to preset JSRESOLVE_* flags and
1609 * returns the index along the prototype chain in which *propp was found, or
1610 * the last index if not found, or -1 on error.
1612 extern int
1613 js_LookupPropertyWithFlags(JSContext *cx, JSObject *obj, jsid id, uintN flags,
1614 JSObject **objp, JSProperty **propp);
1618 * We cache name lookup results only for the global object or for native
1619 * non-global objects without prototype or with prototype that never mutates,
1620 * see bug 462734 and bug 487039.
1622 inline bool
1623 js_IsCacheableNonGlobalScope(JSObject *obj)
1625 extern JS_FRIEND_DATA(js::Class) js_CallClass;
1626 extern JS_FRIEND_DATA(js::Class) js_DeclEnvClass;
1627 JS_ASSERT(obj->getParent());
1629 js::Class *clasp = obj->getClass();
1630 bool cacheable = (clasp == &js_CallClass ||
1631 clasp == &js_BlockClass ||
1632 clasp == &js_DeclEnvClass);
1634 JS_ASSERT_IF(cacheable, !obj->getOps()->lookupProperty);
1635 return cacheable;
1639 * If cacheResult is false, return JS_NO_PROP_CACHE_FILL on success.
1641 extern js::PropertyCacheEntry *
1642 js_FindPropertyHelper(JSContext *cx, jsid id, JSBool cacheResult,
1643 JSObject **objp, JSObject **pobjp, JSProperty **propp);
1646 * Return the index along the scope chain in which id was found, or the last
1647 * index if not found, or -1 on error.
1649 extern JS_FRIEND_API(JSBool)
1650 js_FindProperty(JSContext *cx, jsid id, JSObject **objp, JSObject **pobjp,
1651 JSProperty **propp);
1653 extern JS_REQUIRES_STACK JSObject *
1654 js_FindIdentifierBase(JSContext *cx, JSObject *scopeChain, jsid id);
1656 extern JSObject *
1657 js_FindVariableScope(JSContext *cx, JSFunction **funp);
1660 * JSGET_CACHE_RESULT is the analogue of JSDNP_CACHE_RESULT for js_GetMethod.
1662 * JSGET_METHOD_BARRIER (the default, hence 0 but provided for documentation)
1663 * enables a read barrier that preserves standard function object semantics (by
1664 * default we assume our caller won't leak a joined callee to script, where it
1665 * would create hazardous mutable object sharing as well as observable identity
1666 * according to == and ===.
1668 * JSGET_NO_METHOD_BARRIER avoids the performance overhead of the method read
1669 * barrier, which is not needed when invoking a lambda that otherwise does not
1670 * leak its callee reference (via arguments.callee or its name).
1672 const uintN JSGET_CACHE_RESULT = 1; // from a caching interpreter opcode
1673 const uintN JSGET_METHOD_BARRIER = 0; // get can leak joined function object
1674 const uintN JSGET_NO_METHOD_BARRIER = 2; // call to joined function can't leak
1677 * NB: js_NativeGet and js_NativeSet are called with the scope containing shape
1678 * (pobj's scope for Get, obj's for Set) locked, and on successful return, that
1679 * scope is again locked. But on failure, both functions return false with the
1680 * scope containing shape unlocked.
1682 extern JSBool
1683 js_NativeGet(JSContext *cx, JSObject *obj, JSObject *pobj, const js::Shape *shape, uintN getHow,
1684 js::Value *vp);
1686 extern JSBool
1687 js_NativeSet(JSContext *cx, JSObject *obj, const js::Shape *shape, bool added,
1688 js::Value *vp);
1690 extern JSBool
1691 js_GetPropertyHelper(JSContext *cx, JSObject *obj, jsid id, uint32 getHow, js::Value *vp);
1693 extern bool
1694 js_GetPropertyHelperWithShape(JSContext *cx, JSObject *obj, JSObject *receiver, jsid id,
1695 uint32 getHow, js::Value *vp,
1696 const js::Shape **shapeOut, JSObject **holderOut);
1698 extern JSBool
1699 js_GetOwnPropertyDescriptor(JSContext *cx, JSObject *obj, jsid id, js::Value *vp);
1701 extern JSBool
1702 js_GetMethod(JSContext *cx, JSObject *obj, jsid id, uintN getHow, js::Value *vp);
1705 * Check whether it is OK to assign an undeclared property with name
1706 * propname of the global object in the current script on cx. Reports
1707 * an error if one needs to be reported (in particular in all cases
1708 * when it returns false).
1710 extern JS_FRIEND_API(bool)
1711 js_CheckUndeclaredVarAssignment(JSContext *cx, JSString *propname);
1713 extern JSBool
1714 js_SetPropertyHelper(JSContext *cx, JSObject *obj, jsid id, uintN defineHow,
1715 js::Value *vp, JSBool strict);
1718 * Change attributes for the given native property. The caller must ensure
1719 * that obj is locked and this function always unlocks obj on return.
1721 extern JSBool
1722 js_SetNativeAttributes(JSContext *cx, JSObject *obj, js::Shape *shape,
1723 uintN attrs);
1725 namespace js {
1728 * If obj has a data property methodid which is a function object for the given
1729 * native, return that function object. Otherwise, return NULL.
1731 extern JSObject *
1732 HasNativeMethod(JSObject *obj, jsid methodid, Native native);
1734 extern bool
1735 DefaultValue(JSContext *cx, JSObject *obj, JSType hint, Value *vp);
1737 extern JSBool
1738 CheckAccess(JSContext *cx, JSObject *obj, jsid id, JSAccessMode mode,
1739 js::Value *vp, uintN *attrsp);
1741 } /* namespace js */
1743 extern bool
1744 js_IsDelegate(JSContext *cx, JSObject *obj, const js::Value &v);
1747 * If protoKey is not JSProto_Null, then clasp is ignored. If protoKey is
1748 * JSProto_Null, clasp must non-null.
1750 extern JS_FRIEND_API(JSBool)
1751 js_GetClassPrototype(JSContext *cx, JSObject *scope, JSProtoKey protoKey,
1752 JSObject **protop, js::Class *clasp = NULL);
1754 extern JSBool
1755 js_SetClassPrototype(JSContext *cx, JSObject *ctor, JSObject *proto,
1756 uintN attrs);
1759 * Wrap boolean, number or string as Boolean, Number or String object.
1760 * *vp must not be an object, null or undefined.
1762 extern JSBool
1763 js_PrimitiveToObject(JSContext *cx, js::Value *vp);
1766 * v and vp may alias. On successful return, vp->isObjectOrNull(). If vp is not
1767 * rooted, the caller must root vp before the next possible GC.
1769 extern JSBool
1770 js_ValueToObjectOrNull(JSContext *cx, const js::Value &v, JSObject **objp);
1773 * v and vp may alias. On successful return, vp->isObject(). If vp is not
1774 * rooted, the caller must root vp before the next possible GC.
1776 extern JSObject *
1777 js_ValueToNonNullObject(JSContext *cx, const js::Value &v);
1779 extern JSBool
1780 js_TryValueOf(JSContext *cx, JSObject *obj, JSType type, js::Value *rval);
1782 extern JSBool
1783 js_TryMethod(JSContext *cx, JSObject *obj, JSAtom *atom,
1784 uintN argc, js::Value *argv, js::Value *rval);
1786 extern JSBool
1787 js_XDRObject(JSXDRState *xdr, JSObject **objp);
1789 extern void
1790 js_TraceObject(JSTracer *trc, JSObject *obj);
1792 extern void
1793 js_PrintObjectSlotName(JSTracer *trc, char *buf, size_t bufsize);
1795 extern void
1796 js_ClearNative(JSContext *cx, JSObject *obj);
1798 extern bool
1799 js_GetReservedSlot(JSContext *cx, JSObject *obj, uint32 index, js::Value *vp);
1801 extern bool
1802 js_SetReservedSlot(JSContext *cx, JSObject *obj, uint32 index, const js::Value &v);
1804 extern JSBool
1805 js_CheckPrincipalsAccess(JSContext *cx, JSObject *scopeobj,
1806 JSPrincipals *principals, JSAtom *caller);
1808 /* For CSP -- checks if eval() and friends are allowed to run. */
1809 extern JSBool
1810 js_CheckContentSecurityPolicy(JSContext *cx);
1812 /* NB: Infallible. */
1813 extern const char *
1814 js_ComputeFilename(JSContext *cx, JSStackFrame *caller,
1815 JSPrincipals *principals, uintN *linenop);
1817 extern JSBool
1818 js_ReportGetterOnlyAssignment(JSContext *cx);
1820 extern JS_FRIEND_API(JSBool)
1821 js_GetterOnlyPropertyStub(JSContext *cx, JSObject *obj, jsid id, jsval *vp);
1823 #ifdef DEBUG
1824 JS_FRIEND_API(void) js_DumpChars(const jschar *s, size_t n);
1825 JS_FRIEND_API(void) js_DumpString(JSString *str);
1826 JS_FRIEND_API(void) js_DumpAtom(JSAtom *atom);
1827 JS_FRIEND_API(void) js_DumpObject(JSObject *obj);
1828 JS_FRIEND_API(void) js_DumpValue(const js::Value &val);
1829 JS_FRIEND_API(void) js_DumpId(jsid id);
1830 JS_FRIEND_API(void) js_DumpStackFrame(JSContext *cx, JSStackFrame *start = NULL);
1831 bool IsSaneThisObject(JSObject &obj);
1832 #endif
1834 extern uintN
1835 js_InferFlags(JSContext *cx, uintN defaultFlags);
1837 /* Object constructor native. Exposed only so the JIT can know its address. */
1838 JSBool
1839 js_Object(JSContext *cx, uintN argc, js::Value *vp);
1842 namespace js {
1844 extern bool
1845 SetProto(JSContext *cx, JSObject *obj, JSObject *proto, bool checkForCycles);
1847 extern JSString *
1848 obj_toStringHelper(JSContext *cx, JSObject *obj);
1850 enum EvalType { INDIRECT_EVAL, DIRECT_EVAL };
1853 * Common code implementing direct and indirect eval.
1855 * Evaluate vp[2], if it is a string, in the context of the given calling
1856 * frame, with the provided scope chain, with the semantics of either a direct
1857 * or indirect eval (see ES5 10.4.2). If this is an indirect eval, scopeobj
1858 * must be a global object.
1860 * On success, store the completion value in *vp and return true.
1862 extern bool
1863 EvalKernel(JSContext *cx, uintN argc, js::Value *vp, EvalType evalType, JSStackFrame *caller,
1864 JSObject *scopeobj);
1866 extern bool
1867 IsBuiltinEvalFunction(JSFunction *fun);
1870 #endif /* jsobj_h___ */