Debian Codegraph @

js/public/CallArgs.h

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 /*
8 * [SMDOC] JS::CallArgs API
9 *
10 * Helper classes encapsulating access to the callee, |this| value, arguments,
11 * and argument count for a call/construct operation.
12 *
13 * JS::CallArgs encapsulates access to a JSNative's un-abstracted
14 * |unsigned argc, Value* vp| arguments. The principal way to create a
15 * JS::CallArgs is using JS::CallArgsFromVp:
16 *
17 * // If provided no arguments or a non-numeric first argument, return zero.
18 * // Otherwise return |this| exactly as given, without boxing.
19 * static bool
20 * Func(JSContext* cx, unsigned argc, JS::Value* vp)
21 * {
22 * JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
23 *
24 * // Guard against no arguments or a non-numeric arg0.
25 * if (args.length() == 0 || !args[0].isNumber()) {
26 * args.rval().setInt32(0);
27 * return true;
28 * }
29 *
30 * // Access to the callee must occur before accessing/setting
31 * // the return value.
32 * JSObject& callee = args.callee();
33 * args.rval().setObject(callee);
34 *
35 * // callee() and calleev() will now assert.
36 *
37 * // It's always fine to access thisv().
38 * HandleValue thisv = args.thisv();
39 * args.rval().set(thisv);
40 *
41 * // As the return value was last set to |this|, returns |this|.
42 * return true;
43 * }
44 *
45 * CallArgs is exposed publicly and used internally. Not all parts of its
46 * public interface are meant to be used by embedders! See inline comments to
47 * for details.
48 *
49 * It's possible (albeit deprecated) to manually index into |vp| to access the
50 * callee, |this|, and arguments of a function, and to set its return value.
51 * This does not have the error-handling or moving-GC correctness of CallArgs.
52 * New code should use CallArgs instead whenever possible.
53 *
54 * The eventual plan is to change JSNative to take |const CallArgs&| directly,
55 * for automatic assertion of correct use and to make calling functions more
56 * efficient. Embedders should start internally switching away from using
57 * |argc| and |vp| directly, except to create a |CallArgs|. Then, when an
58 * eventual release making that change occurs, porting efforts will require
59 * changing methods' signatures but won't require invasive changes to the
60 * methods' implementations, potentially under time pressure.
61 */
62
63 #ifndef js_CallArgs_h
64 #define js_CallArgs_h
65
66 #include "mozilla/Assertions.h"
67 #include "mozilla/Attributes.h"
68
69 #include <type_traits>
70
71 #include "jstypes.h"
72
73 #include "js/RootingAPI.h"
74 #include "js/Value.h"
75
76 /* Typedef for native functions called by the JS VM. */
77 using JSNative = bool (*)(JSContext* cx, unsigned argc, JS::Value* vp);
78
79 namespace JS {
80
81 extern JS_PUBLIC_DATA const HandleValue UndefinedHandleValue;
82
83 namespace detail {
84
85 /*
86 * Compute |this| for the |vp| inside a JSNative, either boxing primitives or
87 * replacing with the global object as necessary.
88 */
89 extern JS_PUBLIC_API bool ComputeThis(JSContext* cx, JS::Value* vp,
90 MutableHandleObject thisObject);
91
92 #ifdef JS_DEBUG
93 extern JS_PUBLIC_API void CheckIsValidConstructible(const Value& v);
94 #endif
95
96 class MOZ_STACK_CLASS IncludeUsedRval {
97 mutable bool usedRval_ = false;
98
99 public:
100 bool usedRval() const { return usedRval_; }
101 void setUsedRval() const { usedRval_ = true; }
102 void clearUsedRval() const { usedRval_ = false; }
103 void assertUnusedRval() const { MOZ_ASSERT(!usedRval_); }
104 };
105
106 class MOZ_STACK_CLASS NoUsedRval {
107 public:
108 bool usedRval() const { return false; }
109 void setUsedRval() const {}
110 void clearUsedRval() const {}
111 void assertUnusedRval() const {}
112 };
113
114 template <class WantUsedRval>
115 class MOZ_STACK_CLASS MOZ_NON_PARAM CallArgsBase {
116 static_assert(std::is_same_v<WantUsedRval, IncludeUsedRval> ||
117 std::is_same_v<WantUsedRval, NoUsedRval>,
118 "WantUsedRval can only be IncludeUsedRval or NoUsedRval");
119
120 protected:
121 Value* argv_ = nullptr;
122 unsigned argc_ = 0;
123 bool constructing_ : 1;
124
125 // True if the caller does not use the return value.
126 bool ignoresReturnValue_ : 1;
127
128 #ifdef JS_DEBUG
129 WantUsedRval wantUsedRval_;
130 bool usedRval() const { return wantUsedRval_.usedRval(); }
131 void setUsedRval() const { wantUsedRval_.setUsedRval(); }
132 void clearUsedRval() const { wantUsedRval_.clearUsedRval(); }
133 void assertUnusedRval() const { wantUsedRval_.assertUnusedRval(); }
134 #else
135 bool usedRval() const { return false; }
136 void setUsedRval() const {}
137 void clearUsedRval() const {}
138 void assertUnusedRval() const {}
139 #endif
140
141 CallArgsBase() : constructing_(false), ignoresReturnValue_(false) {}
142
143 public:
144 // CALLEE ACCESS
145
146 /*
147 * Returns the function being called, as a value. Must not be called after
148 * rval() has been used!
149 */
150 HandleValue calleev() const {
151 this->assertUnusedRval();
152 return HandleValue::fromMarkedLocation(&argv_[-2]);
153 }
154
155 /*
156 * Returns the function being called, as an object. Must not be called
157 * after rval() has been used!
158 */
159 JSObject& callee() const { return calleev().toObject(); }
160
161 // CALLING/CONSTRUCTING-DIFFERENTIATIONS
162
163 bool isConstructing() const {
164 #ifdef JS_DEBUG
165 if (constructing_ && !this->usedRval()) {
166 CheckIsValidConstructible(calleev());
167 }
168 #endif
169 return constructing_;
170 }
171
172 bool ignoresReturnValue() const { return ignoresReturnValue_; }
173
174 MutableHandleValue newTarget() const {
175 MOZ_ASSERT(constructing_);
176 return MutableHandleValue::fromMarkedLocation(&this->argv_[argc_]);
177 }
178
179 /*
180 * Returns the |this| value passed to the function. This method must not
181 * be called when the function is being called as a constructor via |new|.
182 * The value may or may not be an object: it is the individual function's
183 * responsibility to box the value if needed.
184 */
185 HandleValue thisv() const {
186 // Some internal code uses thisv() in constructing cases, so don't do
187 // this yet.
188 // MOZ_ASSERT(!argv_[-1].isMagic(JS_IS_CONSTRUCTING));
189 return HandleValue::fromMarkedLocation(&argv_[-1]);
190 }
191
192 bool computeThis(JSContext* cx, MutableHandleObject thisObject) const {
193 if (thisv().isObject()) {
194 thisObject.set(&thisv().toObject());
195 return true;
196 }
197
198 return ComputeThis(cx, base(), thisObject);
199 }
200
201 // ARGUMENTS
202
203 /* Returns the number of arguments. */
204 unsigned length() const { return argc_; }
205
206 /* Returns the i-th zero-indexed argument. */
207 MutableHandleValue operator[](unsigned i) const {
208 MOZ_RELEASE_ASSERT(i < argc_);
209 return MutableHandleValue::fromMarkedLocation(&this->argv_[i]);
210 }
211
212 /*
213 * Returns the i-th zero-indexed argument, or |undefined| if there's no
214 * such argument.
215 */
216 HandleValue get(unsigned i) const {
217 return i < length() ? HandleValue::fromMarkedLocation(&this->argv_[i])
218 : UndefinedHandleValue;
219 }
220
221 /*
222 * Returns true if the i-th zero-indexed argument is present and is not
223 * |undefined|.
224 */
225 bool hasDefined(unsigned i) const {
226 return i < argc_ && !this->argv_[i].isUndefined();
227 }
228
229 // RETURN VALUE
230
231 /*
232 * Returns the currently-set return value. The initial contents of this
233 * value are unspecified. Once this method has been called, callee() and
234 * calleev() can no longer be used. (If you're compiling against a debug
235 * build of SpiderMonkey, these methods will assert to aid debugging.)
236 *
237 * If the method you're implementing succeeds by returning true, you *must*
238 * set this. (SpiderMonkey doesn't currently assert this, but it will do
239 * so eventually.) You don't need to use or change this if your method
240 * fails.
241 */
242 MutableHandleValue rval() const {
243 this->setUsedRval();
244 return MutableHandleValue::fromMarkedLocation(&argv_[-2]);
245 }
246
247 /*
248 * Returns true if there are at least |required| arguments passed in. If
249 * false, it reports an error message on the context.
250 */
251 JS_PUBLIC_API inline bool requireAtLeast(JSContext* cx, const char* fnname,
252 unsigned required) const;
253
254 public:
255 // These methods are publicly exposed, but they are *not* to be used when
256 // implementing a JSNative method and encapsulating access to |vp| within
257 // it. You probably don't want to use these!
258
259 void setCallee(const Value& aCalleev) const {
260 this->clearUsedRval();
261 argv_[-2] = aCalleev;
262 }
263
264 void setThis(const Value& aThisv) const { argv_[-1] = aThisv; }
265
266 MutableHandleValue mutableThisv() const {
267 return MutableHandleValue::fromMarkedLocation(&argv_[-1]);
268 }
269
270 public:
271 // These methods are publicly exposed, but we're unsure of the interfaces
272 // (because they're hackish and drop assertions). Avoid using these if you
273 // can.
274
275 Value* array() const { return argv_; }
276 Value* end() const { return argv_ + argc_ + constructing_; }
277
278 public:
279 // These methods are only intended for internal use. Embedders shouldn't
280 // use them!
281
282 Value* base() const { return argv_ - 2; }
283
284 Value* spAfterCall() const {
285 this->setUsedRval();
286 return argv_ - 1;
287 }
288 };
289
290 } // namespace detail
291
292 class MOZ_STACK_CLASS MOZ_NON_PARAM CallArgs
293 : public detail::CallArgsBase<detail::IncludeUsedRval> {
294 private:
295 friend CallArgs CallArgsFromVp(unsigned argc, Value* vp);
296 friend CallArgs CallArgsFromSp(unsigned stackSlots, Value* sp,
297 bool constructing, bool ignoresReturnValue);
298
299 static CallArgs create(unsigned argc, Value* argv, bool constructing,
300 bool ignoresReturnValue = false) {
301 CallArgs args;
302 args.clearUsedRval();
303 args.argv_ = argv;
304 args.argc_ = argc;
305 args.constructing_ = constructing;
306 args.ignoresReturnValue_ = ignoresReturnValue;
307 #ifdef DEBUG
308 AssertValueIsNotGray(args.thisv());
309 AssertValueIsNotGray(args.calleev());
310 for (unsigned i = 0; i < argc; ++i) {
311 AssertValueIsNotGray(argv[i]);
312 }
313 if (constructing) {
314 AssertValueIsNotGray(args.newTarget());
315 }
316 #endif
317 return args;
318 }
319
320 public:
321 /*
322 * Helper for requireAtLeast to report the actual exception. Public
323 * so we can call it from CallArgsBase and not need multiple
324 * per-template instantiations of it.
325 */
326 static JS_PUBLIC_API void reportMoreArgsNeeded(JSContext* cx,
327 const char* fnname,
328 unsigned required,
329 unsigned actual);
330 };
331
332 namespace detail {
333 template <class WantUsedRval>
334 JS_PUBLIC_API inline bool CallArgsBase<WantUsedRval>::requireAtLeast(
335 JSContext* cx, const char* fnname, unsigned required) const {
336 if (MOZ_LIKELY(required <= length())) {
337 return true;
338 }
339
340 CallArgs::reportMoreArgsNeeded(cx, fnname, required, length());
341 return false;
342 }
343 } // namespace detail
344
345 MOZ_ALWAYS_INLINE CallArgs CallArgsFromVp(unsigned argc, Value* vp) {
346 return CallArgs::create(argc, vp + 2,
347 vp[1].isMagicNoReleaseCheck(JS_IS_CONSTRUCTING));
348 }
349
350 // This method is only intended for internal use in SpiderMonkey. We may
351 // eventually move it to an internal header. Embedders should use
352 // JS::CallArgsFromVp!
353 MOZ_ALWAYS_INLINE CallArgs CallArgsFromSp(unsigned stackSlots, Value* sp,
354 bool constructing = false,
355 bool ignoresReturnValue = false) {
356 return CallArgs::create(stackSlots - constructing, sp - stackSlots,
357 constructing, ignoresReturnValue);
358 }
359
360 } // namespace JS
361
362 #endif /* js_CallArgs_h */