1 /*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #ifdef TEST_TRIGGER_EXCEPTIONS
16 #include <csetjmp>
17 #include <iostream>
18
19 #include "jsvmtest.h"
20
21 static jmp_buf g_buf;
22 static bool g_oomHandlerFinished = false;
23 static bool g_fatalHandlerFinished = false;
24 static bool g_fatalHandlerFinished2 = false;
25 static bool g_promiseRejectFinished = false;
26
OnOOMError(const char * location,const char * detail,bool isHeapOOM)27 void OnOOMError(const char *location, const char *detail, bool isHeapOOM)
28 {
29 g_oomHandlerFinished = true;
30 longjmp(g_buf, 1);
31 }
32
OnFatalError(const char * location,const char * message)33 void OnFatalError(const char *location, const char *message)
34 {
35 g_fatalHandlerFinished = true;
36 longjmp(g_buf, 1);
37 }
38
OnFatalError2(const char * location,const char * message)39 void OnFatalError2(const char *location, const char *message)
40 {
41 g_fatalHandlerFinished2 = true;
42 longjmp(g_buf, 1);
43 }
44
45
OnPromiseReject(JSVM_Env env,JSVM_PromiseRejectEvent rejectEvent,JSVM_Value rejectInfo)46 void OnPromiseReject(JSVM_Env env, JSVM_PromiseRejectEvent rejectEvent, JSVM_Value rejectInfo)
47 {
48 CHECK(jsvm::IsObject(rejectInfo));
49 auto promise = jsvm::GetProperty(rejectInfo, "promise");
50 CHECK(jsvm::IsPromise(promise));
51 auto value = jsvm::GetProperty(rejectInfo, "value");
52 CHECK(jsvm::IsNumber(value));
53 g_promiseRejectFinished = true;
54 }
55
TEST(OOM)56 TEST(OOM)
57 {
58 g_oomHandlerFinished = false;
59 JSVMTEST_CALL(OH_JSVM_SetHandlerForOOMError(vm, OnOOMError));
60 }
61
TEST(FatalError)62 TEST(FatalError)
63 {
64 g_fatalHandlerFinished = false;
65 JSVMTEST_CALL(OH_JSVM_SetHandlerForFatalError(vm, OnFatalError));
66 static bool fataled = false;
67 setjmp(g_buf);
68 if (!fataled) {
69 fataled = true;
70 jsvm::TryTriggerFatalError(vm);
71 }
72 CHECK(g_fatalHandlerFinished);
73 }
74
TEST(PromiseReject)75 TEST(PromiseReject)
76 {
77 JSVMTEST_CALL(OH_JSVM_SetHandlerForPromiseReject(vm, OnPromiseReject));
78 jsvm::Run("new Promise((resolve, reject) => { reject(42); })");
79 }
80
TEST(CheckHandler)81 TEST(CheckHandler)
82 {
83 CHECK(g_fatalHandlerFinished);
84 CHECK(g_promiseRejectFinished);
85 }
86 #endif // TEST_TRIGGER_EXCEPTIONS