forked from Samsung/escargot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExecutionPauser.cpp
More file actions
374 lines (328 loc) · 16.9 KB
/
ExecutionPauser.cpp
File metadata and controls
374 lines (328 loc) · 16.9 KB
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
/*
* Copyright (c) 2019-present Samsung Electronics Co., Ltd
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
#include "Escargot.h"
#include "ExecutionPauser.h"
#include "runtime/GeneratorObject.h"
#include "runtime/AsyncGeneratorObject.h"
#include "runtime/ScriptAsyncFunctionObject.h"
#include "runtime/Environment.h"
#include "runtime/EnvironmentRecord.h"
#include "runtime/IteratorObject.h"
#include "runtime/PromiseObject.h"
#include "interpreter/ByteCodeInterpreter.h"
namespace Escargot {
COMPILE_ASSERT((int)ExecutionPauser::PauseReason::Yield == (int)ExecutionPause::Yield, "");
COMPILE_ASSERT((int)ExecutionPauser::PauseReason::Await == (int)ExecutionPause::Await, "");
COMPILE_ASSERT((int)ExecutionPauser::PauseReason::GeneratorsInitialize == (int)ExecutionPause::GeneratorsInitialize, "");
void* ExecutionPauser::operator new(size_t size)
{
ASSERT(size == sizeof(ExecutionPauser));
static MAY_THREAD_LOCAL bool typeInited = false;
static MAY_THREAD_LOCAL GC_descr descr;
if (!typeInited) {
GC_word desc[GC_BITMAP_SIZE(ExecutionPauser)] = { 0 };
GC_set_bit(desc, GC_WORD_OFFSET(ExecutionPauser, m_executionState));
GC_set_bit(desc, GC_WORD_OFFSET(ExecutionPauser, m_sourceObject));
GC_set_bit(desc, GC_WORD_OFFSET(ExecutionPauser, m_registerFile));
GC_set_bit(desc, GC_WORD_OFFSET(ExecutionPauser, m_byteCodeBlock));
GC_set_bit(desc, GC_WORD_OFFSET(ExecutionPauser, m_pausedCode));
GC_set_bit(desc, GC_WORD_OFFSET(ExecutionPauser, m_pauseValue));
GC_set_bit(desc, GC_WORD_OFFSET(ExecutionPauser, m_resumeValue));
GC_set_bit(desc, GC_WORD_OFFSET(ExecutionPauser, m_promiseCapability.m_promise));
GC_set_bit(desc, GC_WORD_OFFSET(ExecutionPauser, m_promiseCapability.m_resolveFunction));
GC_set_bit(desc, GC_WORD_OFFSET(ExecutionPauser, m_promiseCapability.m_rejectFunction));
descr = GC_make_descriptor(desc, GC_WORD_LEN(ExecutionPauser));
typeInited = true;
}
return GC_MALLOC_EXPLICITLY_TYPED(size, descr);
}
ExecutionPauser::ExecutionPauser(ExecutionState& state, Object* sourceObject, ExecutionState* executionState, Value* registerFile, ByteCodeBlock* blk)
: m_executionState(executionState)
, m_sourceObject(sourceObject)
, m_registerFile(registerFile)
, m_byteCodeBlock(blk)
, m_byteCodePosition(SIZE_MAX)
, m_resumeByteCodePosition(SIZE_MAX)
, m_pauseValue(nullptr)
, m_resumeValueIndex(REGISTER_LIMIT)
, m_resumeStateIndex(REGISTER_LIMIT)
#ifdef ESCARGOT_DEBUGGER
, m_savedStackTrace(nullptr)
#endif /* ESCARGOT_DEBUGGER */
{
}
class ExecutionPauserExecutionStateParentBinder {
public:
ExecutionPauserExecutionStateParentBinder(ExecutionState& state, ExecutionState* originalState)
: m_originalState(originalState)
{
m_oldParent = m_originalState->parent();
ExecutionState* pstate = m_originalState;
while (pstate) {
if (pstate == &state) {
// AsyncGeneratorObject::asyncGeneratorResolve can make loop
return;
}
pstate = pstate->parent();
}
m_originalState->setParent(&state);
}
~ExecutionPauserExecutionStateParentBinder()
{
m_originalState->setParent(m_oldParent);
}
ExecutionState* m_originalState;
ExecutionState* m_oldParent;
};
Value ExecutionPauser::start(ExecutionState& state, ExecutionPauser* self, Object* source, const Value& resumeValue, bool isAbruptReturn, bool isAbruptThrow, StartFrom from)
{
ExecutionState* originalState = self->m_executionState;
while (!originalState->pauseSource()) {
originalState = originalState->parent();
}
ExecutionPauserExecutionStateParentBinder parentBinder(state, originalState);
if (self->m_resumeValueIndex != REGISTER_LIMIT) {
self->m_registerFile[self->m_resumeValueIndex] = resumeValue;
}
if (self->m_resumeStateIndex != REGISTER_LIMIT) {
if (isAbruptThrow) {
self->m_registerFile[self->m_resumeStateIndex] = Value(ResumeState::Throw);
} else if (isAbruptReturn) {
self->m_registerFile[self->m_resumeStateIndex] = Value(ResumeState::Return);
} else {
self->m_registerFile[self->m_resumeStateIndex] = Value(ResumeState::Normal);
}
}
self->m_resumeValue = resumeValue;
if (self->m_resumeByteCodePosition != SIZE_MAX) {
ExecutionResume* gr = (ExecutionResume*)(self->m_pausedCode.data() + self->m_resumeByteCodePosition);
gr->m_needsReturn = isAbruptReturn;
gr->m_needsThrow = isAbruptThrow;
}
// AsyncFunction
// https://www.ecma-international.org/ecma-262/10.0/index.html#sec-async-functions-abstract-operations-async-function-start
// AsyncGeneratorFunction
// https://www.ecma-international.org/ecma-262/10.0/index.html#sec-asyncgeneratorstart
Value result;
try {
ExecutionState* es;
size_t startPos = self->m_byteCodePosition;
if (startPos == SIZE_MAX) {
// need to fresh start
startPos = 0;
es = self->m_executionState;
} else {
// resume
startPos = (size_t)self->m_pausedCode.data() - (size_t)self->m_byteCodeBlock->m_code.data();
LexicalEnvironment* env;
if (originalState->resolveCallee() && originalState->resolveCallee()->isScriptFunctionObject()) {
env = new LexicalEnvironment(new FunctionEnvironmentRecordOnHeap<false, false>(originalState->resolveCallee()->asScriptFunctionObject()), nullptr
#ifndef NDEBUG
,
true
#endif
);
} else {
// top-level-await
env = new LexicalEnvironment(new FunctionEnvironmentRecordOnHeap<false, false>(self->m_sourceObject->asScriptAsyncFunctionObject()), nullptr
#ifndef NDEBUG
,
true
#endif
);
}
es = new ExecutionState(&state, env, false);
}
#ifdef ESCARGOT_DEBUGGER
Debugger* debugger = state.context()->debugger();
ExecutionState* activeSavedStackTraceExecutionState = ESCARGOT_DEBUGGER_NO_STACK_TRACE_RESTORE;
Debugger::SavedStackTraceDataVector* activeSavedStackTrace = nullptr;
if (debugger != nullptr && self->m_savedStackTrace != nullptr) {
activeSavedStackTraceExecutionState = debugger->activeSavedStackTraceExecutionState();
activeSavedStackTrace = debugger->activeSavedStackTrace();
debugger->setActiveSavedStackTrace(&state, self->m_savedStackTrace);
}
#endif /* ESCARGOT_DEBUGGER */
result = ByteCodeInterpreter::interpret(es, self->m_byteCodeBlock, startPos, self->m_registerFile);
#ifdef ESCARGOT_DEBUGGER
if (activeSavedStackTraceExecutionState != ESCARGOT_DEBUGGER_NO_STACK_TRACE_RESTORE) {
debugger->setActiveSavedStackTrace(activeSavedStackTraceExecutionState, activeSavedStackTrace);
}
debugger = state.context()->debugger();
if (from != Generator && self->m_savedStackTrace == nullptr && debugger != nullptr) {
self->m_savedStackTrace = Debugger::saveStackTrace(state);
}
#endif /* ESCARGOT_DEBUGGER */
if (self->m_pauseValue) {
PauseValue* exitValue = self->m_pauseValue;
self->m_pauseValue = nullptr;
result = exitValue->m_value;
auto pauseReason = exitValue->m_pauseReason;
if (pauseReason == ExecutionPauser::PauseReason::GeneratorsInitialize) {
return result;
}
if (from == StartFrom::Generator) {
if (source->asGeneratorObject()->m_generatorState >= GeneratorObject::GeneratorState::CompletedReturn) {
return IteratorObject::createIterResultObject(state, result, true);
}
return result;
} else if (from == StartFrom::Async) {
// https://www.ecma-international.org/ecma-262/10.0/index.html#sec-async-functions-abstract-operations-async-function-start
// Return Completion { [[Type]]: return, [[Value]]: promiseCapability.[[Promise]], [[Target]]: empty }.
result = self->m_promiseCapability.m_promise;
}
} else {
// normal execution end
if (from == StartFrom::Generator) {
source->asGeneratorObject()->m_generatorState = GeneratorObject::GeneratorState::CompletedReturn;
result = IteratorObject::createIterResultObject(state, result, true);
} else if (from == StartFrom::AsyncGenerator) {
source->asAsyncGeneratorObject()->m_asyncGeneratorState = AsyncGeneratorObject::Completed;
result = AsyncGeneratorObject::asyncGeneratorResolve(state, source->asAsyncGeneratorObject(), result, true);
} else {
ASSERT(from == StartFrom::Async);
Value argv = result;
Object::call(state, self->m_promiseCapability.m_resolveFunction, Value(), 1, &argv);
result = self->m_promiseCapability.m_promise;
}
self->release();
}
} catch (const Value& thrownValue) {
auto promiseCapability = self->m_promiseCapability;
self->release();
if (from == StartFrom::Generator) {
ASSERT(from == StartFrom::Generator);
source->asGeneratorObject()->m_generatorState = GeneratorObject::GeneratorState::CompletedThrow;
throw thrownValue;
} else if (from == StartFrom::AsyncGenerator) {
if (source->asAsyncGeneratorObject()->m_asyncGeneratorState == AsyncGeneratorObject::SuspendedStart) {
throw thrownValue;
} else {
source->asAsyncGeneratorObject()->m_asyncGeneratorState = AsyncGeneratorObject::Completed;
result = AsyncGeneratorObject::asyncGeneratorReject(state, source->asAsyncGeneratorObject(), thrownValue);
}
} else {
// https://www.ecma-international.org/ecma-262/10.0/index.html#sec-async-functions-abstract-operations-async-function-start
ASSERT(from == StartFrom::Async);
Value argv = thrownValue;
Object::call(state, promiseCapability.m_rejectFunction, Value(), 1, &argv);
// Return Completion { [[Type]]: return, [[Value]]: promiseCapability.[[Promise]], [[Target]]: empty }.
result = promiseCapability.m_promise;
}
}
return result;
}
void ExecutionPauser::pause(ExecutionState& state, Value returnValue, size_t tailDataPosition, size_t tailDataLength, size_t nextProgramCounter, ByteCodeRegisterIndex dstRegisterIndex, ByteCodeRegisterIndex dstStateRegisterIndex, PauseReason reason)
{
ExecutionState* originalState = &state;
ExecutionPauser* self;
while (true) {
originalState->m_inExecutionStopState = true;
self = originalState->pauseSource();
if (self) {
break;
}
originalState = originalState->parent();
}
Object* pauser = self->m_sourceObject;
self->m_executionState = &state;
self->m_byteCodePosition = nextProgramCounter;
self->m_resumeValueIndex = dstRegisterIndex;
self->m_resumeStateIndex = dstStateRegisterIndex;
bool isGenerator = pauser->isGeneratorObject();
bool isAsyncGenerator = pauser->isAsyncGeneratorObject();
if (reason == PauseReason::Yield) {
if (isGenerator) {
pauser->asGeneratorObject()->m_generatorState = GeneratorObject::GeneratorState::SuspendedYield;
} else if (isAsyncGenerator) {
pauser->asAsyncGeneratorObject()->m_asyncGeneratorState = AsyncGeneratorObject::AsyncGeneratorState::SuspendedYield;
returnValue = AsyncGeneratorObject::asyncGeneratorResolve(state, pauser->asAsyncGeneratorObject(), returnValue, false);
}
} else {
ASSERT(reason == PauseReason::Await || reason == PauseReason::GeneratorsInitialize);
}
// we need to reset parent here beacuse asyncGeneratorResolve access parent
originalState->rareData()->m_parent = nullptr;
self->m_pausedCode.clear();
// some case(async generator), the function execution ended before pause
if (self->m_byteCodeBlock) {
// read & fill recursive statement self
char* start = (char*)(tailDataPosition);
char* end = (char*)(start + tailDataLength);
size_t startupDataPosition = self->m_pausedCode.size();
std::vector<size_t> codeStartPositions;
size_t codePos = startupDataPosition;
while (start != end) {
size_t e = *((size_t*)start);
start += sizeof(ByteCodeGenerateContext::RecursiveStatementKind);
size_t startPos = *((size_t*)start);
codeStartPositions.push_back(startPos);
if (e == ByteCodeGenerateContext::Block) {
self->m_pausedCode.resizeWithUninitializedValues(self->m_pausedCode.size() + sizeof(BlockOperation));
BlockOperation* code = new (self->m_pausedCode.data() + codePos) BlockOperation(ByteCodeLOC(SIZE_MAX), nullptr);
code->assignOpcodeInAddress();
codePos += sizeof(BlockOperation);
} else if (e == ByteCodeGenerateContext::OpenEnv) {
self->m_pausedCode.resizeWithUninitializedValues(self->m_pausedCode.size() + sizeof(OpenLexicalEnvironment));
OpenLexicalEnvironment* code = new (self->m_pausedCode.data() + codePos) OpenLexicalEnvironment(ByteCodeLOC(SIZE_MAX), OpenLexicalEnvironment::ResumeExecution, REGISTER_LIMIT);
code->assignOpcodeInAddress();
codePos += sizeof(OpenLexicalEnvironment);
} else if (e == ByteCodeGenerateContext::Try) {
self->m_pausedCode.resizeWithUninitializedValues(self->m_pausedCode.size() + sizeof(TryOperation));
TryOperation* code = new (self->m_pausedCode.data() + codePos) TryOperation(ByteCodeLOC(SIZE_MAX));
code->assignOpcodeInAddress();
code->m_isTryResumeProcess = true;
codePos += sizeof(TryOperation);
} else if (e == ByteCodeGenerateContext::Catch) {
self->m_pausedCode.resizeWithUninitializedValues(self->m_pausedCode.size() + sizeof(TryOperation));
TryOperation* code = new (self->m_pausedCode.data() + codePos) TryOperation(ByteCodeLOC(SIZE_MAX));
code->assignOpcodeInAddress();
code->m_isCatchResumeProcess = true;
codePos += sizeof(TryOperation);
} else {
ASSERT(e == ByteCodeGenerateContext::Finally);
self->m_pausedCode.resizeWithUninitializedValues(self->m_pausedCode.size() + sizeof(TryOperation));
TryOperation* code = new (self->m_pausedCode.data() + codePos) TryOperation(ByteCodeLOC(SIZE_MAX));
code->assignOpcodeInAddress();
code->m_isFinallyResumeProcess = true;
codePos += sizeof(TryOperation);
}
start += sizeof(size_t); // start pos
}
size_t resumeCodePos = self->m_pausedCode.size();
self->m_resumeByteCodePosition = resumeCodePos;
self->m_pausedCode.resizeWithUninitializedValues(resumeCodePos + sizeof(ExecutionResume));
auto resumeCode = new (self->m_pausedCode.data() + resumeCodePos) ExecutionResume(ByteCodeLOC(SIZE_MAX), self);
resumeCode->assignOpcodeInAddress();
size_t stackSizePos = self->m_pausedCode.size();
self->m_pausedCode.resizeWithUninitializedValues(stackSizePos + sizeof(size_t));
new (self->m_pausedCode.data() + stackSizePos) size_t(codeStartPositions.size());
// add ByteCodePositions
for (size_t i = 0; i < codeStartPositions.size(); i++) {
size_t pos = self->m_pausedCode.size();
self->m_pausedCode.resizeWithUninitializedValues(pos + sizeof(size_t));
new (self->m_pausedCode.data() + pos) size_t(codeStartPositions[i]);
}
}
PauseValue* exitValue = new PauseValue();
exitValue->m_value = returnValue;
exitValue->m_pauseReason = (ExecutionPauser::PauseReason)reason;
self->m_pauseValue = exitValue;
}
} // namespace Escargot