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