Debian Codegraph @

js/src/jsapi-tests/tests.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 #ifndef jsapi_tests_tests_h
8 #define jsapi_tests_tests_h
9
10 #include "mozilla/Sprintf.h"
11
12 #include <errno.h>
13 #include <iterator>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <type_traits>
18
19 #include "jsapi.h"
20
21 #include "gc/GC.h"
22 #include "js/AllocPolicy.h"
23 #include "js/ArrayBuffer.h"
24 #include "js/CharacterEncoding.h"
25 #include "js/Conversions.h"
26 #include "js/Equality.h" // JS::SameValue
27 #include "js/GlobalObject.h" // JS::DefaultGlobalClassOps
28 #include "js/RegExpFlags.h" // JS::RegExpFlags
29 #include "js/Vector.h"
30 #include "js/Warnings.h" // JS::SetWarningReporter
31 #include "vm/JSContext.h"
32
33 /* Note: Aborts on OOM. */
34 class JSAPITestString {
35 js::Vector<char, 0, js::SystemAllocPolicy> chars;
36
37 public:
38 JSAPITestString() {}
39 explicit JSAPITestString(const char* s) { *this += s; }
40 JSAPITestString(const JSAPITestString& s) { *this += s; }
41
42 const char* begin() const { return chars.begin(); }
43 const char* end() const { return chars.end(); }
44 size_t length() const { return chars.length(); }
45 void clear() { chars.clearAndFree(); }
46
47 JSAPITestString& operator+=(const char* s) {
48 if (!chars.append(s, strlen(s))) {
49 abort();
50 }
51 return *this;
52 }
53
54 JSAPITestString& operator+=(const JSAPITestString& s) {
55 if (!chars.append(s.begin(), s.length())) {
56 abort();
57 }
58 return *this;
59 }
60 };
61
62 inline JSAPITestString operator+(const JSAPITestString& a, const char* b) {
63 JSAPITestString result = a;
64 result += b;
65 return result;
66 }
67
68 inline JSAPITestString operator+(const JSAPITestString& a,
69 const JSAPITestString& b) {
70 JSAPITestString result = a;
71 result += b;
72 return result;
73 }
74
75 class JSAPIRuntimeTest;
76
77 class JSAPITest {
78 public:
79 bool knownFail;
80 JSAPITestString msgs;
81
82 JSAPITest() : knownFail(false) {}
83
84 virtual ~JSAPITest() {}
85
86 virtual const char* name() = 0;
87
88 virtual void maybeAppendException(JSAPITestString& message) {}
89
90 bool fail(const JSAPITestString& msg = JSAPITestString(),
91 const char* filename = "-", int lineno = 0) {
92 char location[256];
93 SprintfLiteral(location, "%s:%d:", filename, lineno);
94
95 JSAPITestString message(location);
96 message += msg;
97
98 maybeAppendException(message);
99
100 fprintf(stderr, "%.*s\n", int(message.length()), message.begin());
101
102 if (msgs.length() != 0) {
103 msgs += " | ";
104 }
105 msgs += message;
106 return false;
107 }
108
109 JSAPITestString messages() const { return msgs; }
110 };
111
112 class JSAPIRuntimeTest : public JSAPITest {
113 public:
114 static JSAPIRuntimeTest* list;
115 JSAPIRuntimeTest* next;
116
117 JSContext* cx;
118 JS::PersistentRootedObject global;
119
120 // Whether this test is willing to skip its init() and reuse a global (and
121 // JSContext etc.) from a previous test that also has reuseGlobal=true. It
122 // also means this test is willing to skip its uninit() if it is followed by
123 // another reuseGlobal test.
124 bool reuseGlobal;
125
126 JSAPIRuntimeTest() : JSAPITest(), cx(nullptr), reuseGlobal(false) {
127 next = list;
128 list = this;
129 }
130
131 virtual ~JSAPIRuntimeTest() {
132 MOZ_RELEASE_ASSERT(!cx);
133 MOZ_RELEASE_ASSERT(!global);
134 }
135
136 // Initialize this test, possibly with the cx from a previously run test.
137 bool init(JSContext* maybeReusedContext);
138
139 // If this test is ok with its cx and global being reused, release this
140 // test's cx to be reused by another test.
141 JSContext* maybeForgetContext();
142
143 static void MaybeFreeContext(JSContext* maybeCx);
144
145 // The real initialization happens in init(JSContext*), above, but this
146 // method may be overridden to perform additional initialization after the
147 // JSContext and global have been created.
148 virtual bool init() { return true; }
149 virtual void uninit();
150
151 virtual bool run(JS::HandleObject global) = 0;
152
153 #define EXEC(s) \
154 do { \
155 if (!exec(s, __FILE__, __LINE__)) return false; \
156 } while (false)
157
158 bool exec(const char* utf8, const char* filename, int lineno);
159
160 // Like exec(), but doesn't call fail() if JS::Evaluate returns false.
161 bool execDontReport(const char* utf8, const char* filename, int lineno);
162
163 #define EVAL(s, vp) \
164 do { \
165 if (!evaluate(s, __FILE__, __LINE__, vp)) return false; \
166 } while (false)
167
168 bool evaluate(const char* utf8, const char* filename, int lineno,
169 JS::MutableHandleValue vp);
170
171 JSAPITestString jsvalToSource(JS::HandleValue v) {
172 JS::Rooted<JSString*> str(cx, JS_ValueToSource(cx, v));
173 if (str) {
174 if (JS::UniqueChars bytes = JS_EncodeStringToUTF8(cx, str)) {
175 return JSAPITestString(bytes.get());
176 }
177 }
178 JS_ClearPendingException(cx);
179 return JSAPITestString("<<error converting value to string>>");
180 }
181
182 JSAPITestString toSource(char c) {
183 char buf[2] = {c, '\0'};
184 return JSAPITestString(buf);
185 }
186
187 JSAPITestString toSource(long v) {
188 char buf[40];
189 SprintfLiteral(buf, "%ld", v);
190 return JSAPITestString(buf);
191 }
192
193 JSAPITestString toSource(unsigned long v) {
194 char buf[40];
195 SprintfLiteral(buf, "%lu", v);
196 return JSAPITestString(buf);
197 }
198
199 JSAPITestString toSource(long long v) {
200 char buf[40];
201 SprintfLiteral(buf, "%lld", v);
202 return JSAPITestString(buf);
203 }
204
205 JSAPITestString toSource(unsigned long long v) {
206 char buf[40];
207 SprintfLiteral(buf, "%llu", v);
208 return JSAPITestString(buf);
209 }
210
211 JSAPITestString toSource(double d) {
212 char buf[40];
213 SprintfLiteral(buf, "%17lg", d);
214 return JSAPITestString(buf);
215 }
216
217 JSAPITestString toSource(unsigned int v) {
218 return toSource((unsigned long)v);
219 }
220
221 JSAPITestString toSource(int v) { return toSource((long)v); }
222
223 JSAPITestString toSource(bool v) {
224 return JSAPITestString(v ? "true" : "false");
225 }
226
227 JSAPITestString toSource(JS::RegExpFlags flags) {
228 JSAPITestString str;
229 if (flags.hasIndices()) {
230 str += "d";
231 }
232 if (flags.global()) {
233 str += "g";
234 }
235 if (flags.ignoreCase()) {
236 str += "i";
237 }
238 if (flags.multiline()) {
239 str += "m";
240 }
241 if (flags.dotAll()) {
242 str += "s";
243 }
244 if (flags.unicode()) {
245 str += "u";
246 }
247 if (flags.unicodeSets()) {
248 str += "v";
249 }
250 if (flags.sticky()) {
251 str += "y";
252 }
253 return str;
254 }
255
256 JSAPITestString toSource(JSAtom* v) {
257 JS::RootedValue val(cx, JS::StringValue((JSString*)v));
258 return jsvalToSource(val);
259 }
260
261 // Note that in some still-supported GCC versions (we think anything before
262 // GCC 4.6), this template does not work when the second argument is
263 // nullptr. It infers type U = long int. Use CHECK_NULL instead.
264 template <typename T, typename U>
265 bool checkEqual(const T& actual, const U& expected, const char* actualExpr,
266 const char* expectedExpr, const char* filename, int lineno) {
267 static_assert(std::is_signed_v<T> == std::is_signed_v<U>,
268 "using CHECK_EQUAL with different-signed inputs triggers "
269 "compiler warnings");
270 static_assert(
271 std::is_unsigned_v<T> == std::is_unsigned_v<U>,
272 "using CHECK_EQUAL with different-signed inputs triggers compiler "
273 "warnings");
274 return (actual == expected) ||
275 fail(JSAPITestString("CHECK_EQUAL failed: expected (") +
276 expectedExpr + ") = " + toSource(expected) + ", got (" +
277 actualExpr + ") = " + toSource(actual),
278 filename, lineno);
279 }
280
281 #define CHECK_EQUAL(actual, expected) \
282 do { \
283 if (!checkEqual(actual, expected, #actual, #expected, __FILE__, __LINE__)) \
284 return false; \
285 } while (false)
286
287 template <typename T>
288 bool checkNull(const T* actual, const char* actualExpr, const char* filename,
289 int lineno) {
290 return (actual == nullptr) ||
291 fail(JSAPITestString("CHECK_NULL failed: expected nullptr, got (") +
292 actualExpr + ") = " + toSource(actual),
293 filename, lineno);
294 }
295
296 #define CHECK_NULL(actual) \
297 do { \
298 if (!checkNull(actual, #actual, __FILE__, __LINE__)) return false; \
299 } while (false)
300
301 bool checkSame(const JS::Value& actualArg, const JS::Value& expectedArg,
302 const char* actualExpr, const char* expectedExpr,
303 const char* filename, int lineno) {
304 bool same;
305 JS::RootedValue actual(cx, actualArg), expected(cx, expectedArg);
306 return (JS::SameValue(cx, actual, expected, &same) && same) ||
307 fail(JSAPITestString(
308 "CHECK_SAME failed: expected JS::SameValue(cx, ") +
309 actualExpr + ", " + expectedExpr +
310 "), got !JS::SameValue(cx, " + jsvalToSource(actual) +
311 ", " + jsvalToSource(expected) + ")",
312 filename, lineno);
313 }
314
315 #define CHECK_SAME(actual, expected) \
316 do { \
317 if (!checkSame(actual, expected, #actual, #expected, __FILE__, __LINE__)) \
318 return false; \
319 } while (false)
320
321 #define CHECK(expr) \
322 do { \
323 if (!(expr)) \
324 return fail(JSAPITestString("CHECK failed: " #expr), __FILE__, \
325 __LINE__); \
326 } while (false)
327
328 void maybeAppendException(JSAPITestString& message) override {
329 if (JS_IsExceptionPending(cx)) {
330 message += " -- ";
331
332 js::gc::AutoSuppressGC gcoff(cx);
333 JS::RootedValue v(cx);
334 JS_GetPendingException(cx, &v);
335 JS_ClearPendingException(cx);
336 JS::Rooted<JSString*> s(cx, JS::ToString(cx, v));
337 if (s) {
338 if (JS::UniqueChars bytes = JS_EncodeStringToLatin1(cx, s)) {
339 message += bytes.get();
340 }
341 }
342 }
343 }
344
345 static const JSClass* basicGlobalClass() {
346 static const JSClass c = {
347 "global",
348 JSCLASS_GLOBAL_FLAGS,
349 &JS::DefaultGlobalClassOps,
350 };
351 return &c;
352 }
353
354 protected:
355 static bool print(JSContext* cx, unsigned argc, JS::Value* vp) {
356 JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
357
358 JS::Rooted<JSString*> str(cx);
359 for (unsigned i = 0; i < args.length(); i++) {
360 str = JS::ToString(cx, args[i]);
361 if (!str) {
362 return false;
363 }
364 JS::UniqueChars bytes = JS_EncodeStringToUTF8(cx, str);
365 if (!bytes) {
366 return false;
367 }
368 printf("%s%s", i ? " " : "", bytes.get());
369 }
370
371 putchar('\n');
372 fflush(stdout);
373 args.rval().setUndefined();
374 return true;
375 }
376
377 bool definePrint();
378
379 virtual JSContext* createContext() {
380 JSContext* cx = JS_NewContext(8L * 1024 * 1024);
381 if (!cx) {
382 return nullptr;
383 }
384 JS::SetWarningReporter(cx, &reportWarning);
385 return cx;
386 }
387
388 static void reportWarning(JSContext* cx, JSErrorReport* report) {
389 MOZ_RELEASE_ASSERT(report->isWarning());
390
391 fprintf(stderr, "%s:%u:%s\n",
392 report->filename ? report->filename.c_str() : "<no filename>",
393 (unsigned int)report->lineno, report->message().c_str());
394 }
395
396 virtual const JSClass* getGlobalClass() { return basicGlobalClass(); }
397
398 virtual JSObject* createGlobal(JSPrincipals* principals = nullptr);
399 };
400
401 class JSAPIFrontendTest : public JSAPITest {
402 public:
403 static JSAPIFrontendTest* list;
404 JSAPIFrontendTest* next;
405
406 JSAPIFrontendTest() : JSAPITest() {
407 next = list;
408 list = this;
409 }
410
411 virtual ~JSAPIFrontendTest() {}
412
413 virtual bool init() { return true; }
414 virtual void uninit() {}
415
416 virtual bool run() = 0;
417 };
418
419 #define BEGIN_TEST_WITH_ATTRIBUTES_AND_EXTRA(testname, attrs, extra) \
420 class cls_##testname : public JSAPIRuntimeTest { \
421 public: \
422 virtual const char* name() override { return #testname; } \
423 extra virtual bool run(JS::HandleObject global) override attrs
424
425 #define BEGIN_TEST_WITH_ATTRIBUTES(testname, attrs) \
426 BEGIN_TEST_WITH_ATTRIBUTES_AND_EXTRA(testname, attrs, )
427
428 #define BEGIN_TEST(testname) BEGIN_TEST_WITH_ATTRIBUTES(testname, )
429
430 #define BEGIN_FRONTEND_TEST_WITH_ATTRIBUTES_AND_EXTRA(testname, attrs, extra) \
431 class cls_##testname : public JSAPIFrontendTest { \
432 public: \
433 virtual const char* name() override { return #testname; } \
434 extra virtual bool run() override attrs
435
436 #define BEGIN_FRONTEND_TEST_WITH_ATTRIBUTES(testname, attrs) \
437 BEGIN_FRONTEND_TEST_WITH_ATTRIBUTES_AND_EXTRA(testname, attrs, )
438
439 #define BEGIN_FRONTEND_TEST(testname) \
440 BEGIN_FRONTEND_TEST_WITH_ATTRIBUTES(testname, )
441
442 #define BEGIN_REUSABLE_TEST(testname) \
443 BEGIN_TEST_WITH_ATTRIBUTES_AND_EXTRA( \
444 testname, , \
445 cls_##testname() : JSAPIRuntimeTest() { reuseGlobal = true; })
446
447 #define END_TEST(testname) \
448 } \
449 ; \
450 MOZ_RUNINIT static cls_##testname cls_##testname##_instance;
451
452 /*
453 * A "fixture" is a subclass of JSAPIRuntimeTest that holds common definitions
454 * for a set of tests. Each test that wants to use the fixture should use
455 * BEGIN_FIXTURE_TEST and END_FIXTURE_TEST, just as one would use BEGIN_TEST and
456 * END_TEST, but include the fixture class as the first argument. The fixture
457 * class's declarations are then in scope for the test bodies.
458 */
459
460 #define BEGIN_FIXTURE_TEST(fixture, testname) \
461 class cls_##testname : public fixture { \
462 public: \
463 virtual const char* name() override { return #testname; } \
464 virtual bool run(JS::HandleObject global) override
465
466 #define END_FIXTURE_TEST(fixture, testname) \
467 } \
468 ; \
469 MOZ_RUNINIT static cls_##testname cls_##testname##_instance;
470
471 /*
472 * A class for creating and managing one temporary file.
473 *
474 * We could use the ISO C temporary file functions here, but those try to
475 * create files in the root directory on Windows, which fails for users
476 * without Administrator privileges.
477 */
478 class TempFile {
479 const char* name;
480 FILE* stream;
481
482 public:
483 TempFile() : name(), stream() {}
484 ~TempFile() {
485 if (stream) {
486 close();
487 }
488 if (name) {
489 remove();
490 }
491 }
492
493 /*
494 * Return a stream for a temporary file named |fileName|. Infallible.
495 * Use only once per TempFile instance. If the file is not explicitly
496 * closed and deleted via the member functions below, this object's
497 * destructor will clean them up.
498 */
499 FILE* open(const char* fileName) {
500 stream = fopen(fileName, "wb+");
501 if (!stream) {
502 fprintf(stderr, "error opening temporary file '%s': %s\n", fileName,
503 strerror(errno));
504 exit(1);
505 }
506 name = fileName;
507 return stream;
508 }
509
510 /* Close the temporary file's stream. */
511 void close() {
512 if (fclose(stream) == EOF) {
513 fprintf(stderr, "error closing temporary file '%s': %s\n", name,
514 strerror(errno));
515 exit(1);
516 }
517 stream = nullptr;
518 }
519
520 /* Delete the temporary file. */
521 void remove() {
522 if (::remove(name) != 0) {
523 fprintf(stderr, "error deleting temporary file '%s': %s\n", name,
524 strerror(errno));
525 exit(1);
526 }
527 name = nullptr;
528 }
529 };
530
531 // Just a wrapper around JSPrincipals that allows static construction.
532 class TestJSPrincipals : public JSPrincipals {
533 public:
534 explicit TestJSPrincipals(int rc = 0) : JSPrincipals() { refcount = rc; }
535
536 bool write(JSContext* cx, JSStructuredCloneWriter* writer) override {
537 MOZ_ASSERT(false, "not implemented");
538 return false;
539 }
540
541 bool isSystemOrAddonPrincipal() override { return true; }
542 };
543
544 // A class that simulates externally memory-managed data, for testing with
545 // array buffers.
546 class ExternalData {
547 char* contents_;
548 size_t len_;
549 bool uniquePointerCreated_ = false;
550
551 public:
552 explicit ExternalData(const char* str)
553 : contents_(strdup(str)), len_(strlen(str) + 1) {}
554
555 size_t len() const { return len_; }
556 void* contents() const { return contents_; }
557 char* asString() const { return contents_; }
558 bool wasFreed() const { return !contents_; }
559
560 void free() {
561 MOZ_ASSERT(!wasFreed());
562 ::free(contents_);
563 contents_ = nullptr;
564 }
565
566 mozilla::UniquePtr<void, JS::BufferContentsDeleter> pointer() {
567 MOZ_ASSERT(!uniquePointerCreated_,
568 "Not allowed to create multiple unique pointers to contents");
569 uniquePointerCreated_ = true;
570 return {contents_, {ExternalData::freeCallback, this}};
571 }
572
573 static void freeCallback(void* contents, void* userData) {
574 auto self = static_cast<ExternalData*>(userData);
575 MOZ_ASSERT(self->contents() == contents);
576 self->free();
577 }
578 };
579
580 class AutoGCParameter {
581 JSContext* cx_;
582 JSGCParamKey key_;
583 uint32_t value_;
584
585 public:
586 explicit AutoGCParameter(JSContext* cx, JSGCParamKey key, uint32_t value)
587 : cx_(cx), key_(key), value_() {
588 value_ = JS_GetGCParameter(cx, key);
589 JS_SetGCParameter(cx, key, value);
590 }
591 ~AutoGCParameter() { JS_SetGCParameter(cx_, key_, value_); }
592 };
593
594 #ifdef JS_GC_ZEAL
595 /*
596 * Temporarily disable the GC zeal setting. This is only useful in tests that
597 * need very explicit GC behavior and should not be used elsewhere.
598 */
599 class AutoLeaveZeal {
600 JSContext* cx_;
601 uint32_t zealBits_;
602 uint32_t frequency_;
603
604 public:
605 explicit AutoLeaveZeal(JSContext* cx) : cx_(cx), zealBits_(0), frequency_(0) {
606 uint32_t dummy;
607 JS::GetGCZealBits(cx_, &zealBits_, &frequency_, &dummy);
608 JS::SetGCZeal(cx_, 0, 0);
609 JS::PrepareForFullGC(cx_);
610 JS::NonIncrementalGC(cx_, JS::GCOptions::Normal, JS::GCReason::DEBUG_GC);
611 }
612 ~AutoLeaveZeal() {
613 JS::SetGCZeal(cx_, 0, 0);
614 for (size_t i = 0; i < sizeof(zealBits_) * 8; i++) {
615 if (zealBits_ & (1 << i)) {
616 JS::SetGCZeal(cx_, i, frequency_);
617 }
618 }
619
620 # ifdef DEBUG
621 uint32_t zealBitsAfter, frequencyAfter, dummy;
622 JS::GetGCZealBits(cx_, &zealBitsAfter, &frequencyAfter, &dummy);
623 MOZ_ASSERT(zealBitsAfter == zealBits_);
624 MOZ_ASSERT(frequencyAfter == frequency_);
625 # endif
626 }
627 };
628
629 #else
630 class AutoLeaveZeal {
631 public:
632 explicit AutoLeaveZeal(JSContext* cx) {}
633 };
634 #endif
635
636 #endif /* jsapi_tests_tests_h */