-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathJITServer.cpp
993 lines (870 loc) · 29.5 KB
/
JITServer.cpp
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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "JITServerPch.h"
__declspec(dllexport)
HRESULT JsInitializeJITServer(
__in UUID* connectionUuid,
__in_opt void* securityDescriptor,
__in_opt void* alpcSecurityDescriptor)
{
RPC_STATUS status;
RPC_BINDING_VECTOR* bindingVector = NULL;
UUID_VECTOR uuidVector;
uuidVector.Count = 1;
uuidVector.Uuid[0] = connectionUuid;
status = RpcServerUseProtseqW(
(RPC_WSTR)L"ncalrpc",
RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
alpcSecurityDescriptor);
if (status != RPC_S_OK)
{
return status;
}
if (AutoSystemInfo::Data.IsWin8OrLater())
{
status = RPCLibrary::Instance->RpcServerRegisterIf3(
ServerIChakraJIT_v0_0_s_ifspec,
NULL,
NULL,
RPC_IF_AUTOLISTEN,
RPC_C_LISTEN_MAX_CALLS_DEFAULT,
(ULONG)-1,
NULL,
securityDescriptor);
}
else
{
status = RpcServerRegisterIf2(
ServerIChakraJIT_v0_0_s_ifspec,
NULL,
NULL,
RPC_IF_AUTOLISTEN,
RPC_C_LISTEN_MAX_CALLS_DEFAULT,
(ULONG)-1,
NULL);
}
if (status != RPC_S_OK)
{
return status;
}
status = RpcServerInqBindings(&bindingVector);
if (status != RPC_S_OK)
{
return status;
}
JITManager::GetJITManager()->SetIsJITServer();
PageAllocatorPool::Initialize();
status = RpcEpRegister(
ServerIChakraJIT_v0_0_s_ifspec,
bindingVector,
&uuidVector,
NULL);
if (status != RPC_S_OK)
{
return status;
}
status = RpcBindingVectorFree(&bindingVector);
if (status != RPC_S_OK)
{
return status;
}
status = RpcServerListen(1, RPC_C_LISTEN_MAX_CALLS_DEFAULT, FALSE);
return status;
}
HRESULT
ShutdownCommon()
{
HRESULT status = RpcMgmtStopServerListening(NULL);
if (status != RPC_S_OK)
{
return status;
}
status = RpcServerUnregisterIf(ServerIChakraJIT_v0_0_s_ifspec, NULL, FALSE);
ServerContextManager::Shutdown();
PageAllocatorPool::Shutdown();
return status;
}
HRESULT
ServerShutdown(
/* [in] */ handle_t binding)
{
return ShutdownCommon();
}
void
__RPC_USER PTHREADCONTEXT_HANDLE_rundown(__RPC__in PTHREADCONTEXT_HANDLE phContext)
{
ServerCleanupThreadContext(nullptr, &phContext);
}
void
__RPC_USER PSCRIPTCONTEXT_HANDLE_rundown(__RPC__in PSCRIPTCONTEXT_HANDLE phContext)
{
ServerCloseScriptContext(nullptr, phContext);
ServerCleanupScriptContext(nullptr, &phContext);
}
HRESULT
ServerConnectProcessWithProcessHandle(
handle_t binding,
HANDLE processHandle,
intptr_t chakraBaseAddress,
intptr_t crtBaseAddress
)
{
DWORD clientPid;
HRESULT hr = HRESULT_FROM_WIN32(I_RpcBindingInqLocalClientPID(binding, &clientPid));
if (FAILED(hr))
{
return hr;
}
HANDLE targetHandle = nullptr;
// RPC handle marshalling is only available on 8.1+
if (!DuplicateHandle(GetCurrentProcess(), processHandle, GetCurrentProcess(), &targetHandle, 0, false, DUPLICATE_SAME_ACCESS))
{
Assert(UNREACHED);
return E_ACCESSDENIED;
}
return ProcessContextManager::RegisterNewProcess(clientPid, targetHandle, chakraBaseAddress, crtBaseAddress);
}
#if !(WINVER >= _WIN32_WINNT_WINBLUE)
HRESULT
ServerConnectProcess(
handle_t binding,
intptr_t chakraBaseAddress,
intptr_t crtBaseAddress
)
{
// Should use ServerConnectProcessWithProcessHandle on 8.1+
if (AutoSystemInfo::Data.IsWin8Point1OrLater())
{
Assert(UNREACHED);
return E_ACCESSDENIED;
}
DWORD clientPid;
HRESULT hr = HRESULT_FROM_WIN32(I_RpcBindingInqLocalClientPID(binding, &clientPid));
if (FAILED(hr))
{
return hr;
}
HANDLE targetHandle = nullptr;
targetHandle = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION, false, clientPid);
if (!targetHandle)
{
Assert(UNREACHED);
return E_ACCESSDENIED;
}
return ProcessContextManager::RegisterNewProcess(clientPid, targetHandle, chakraBaseAddress, crtBaseAddress);
}
#endif
#pragma warning(push)
#pragma warning(disable:6387 28196) // PREFast does not understand the out context can be null here
HRESULT
ServerInitializeThreadContext(
/* [in] */ handle_t binding,
/* [in] */ __RPC__in ThreadContextDataIDL * threadContextData,
/* [out] */ __RPC__deref_out_opt PPTHREADCONTEXT_HANDLE threadContextInfoAddress,
/* [out] */ __RPC__out intptr_t *prereservedRegionAddr,
/* [out] */ __RPC__out intptr_t *jitThunkAddr)
{
if (threadContextInfoAddress == nullptr || prereservedRegionAddr == nullptr)
{
Assert(false);
return RPC_S_INVALID_ARG;
}
*threadContextInfoAddress = nullptr;
*prereservedRegionAddr = 0;
*jitThunkAddr = 0;
ServerThreadContext * contextInfo = nullptr;
DWORD clientPid;
HRESULT hr = HRESULT_FROM_WIN32(I_RpcBindingInqLocalClientPID(binding, &clientPid));
if (FAILED(hr))
{
return hr;
}
ProcessContext* processContext = ProcessContextManager::GetProcessContext(clientPid);
if (processContext == nullptr)
{
return E_ACCESSDENIED;
}
try
{
AUTO_NESTED_HANDLED_EXCEPTION_TYPE(static_cast<ExceptionType>(ExceptionType_OutOfMemory));
contextInfo = HeapNew(ServerThreadContext, threadContextData, processContext);
ServerContextManager::RegisterThreadContext(contextInfo);
}
catch (Js::OutOfMemoryException)
{
if (contextInfo)
{
// If we OOM while registering the ThreadContext, we need to free it
HeapDelete(contextInfo);
}
else
{
// If we OOM while creating the ThreadContext, then we haven't transfered ownership
// of the ProcessContext reference, so we must release it here
processContext->Release();
}
return E_OUTOFMEMORY;
}
return ServerCallWrapper(contextInfo, [&]()->HRESULT
{
if (clientPid != contextInfo->GetRuntimePid())
{
return E_ACCESSDENIED;
}
*threadContextInfoAddress = (PTHREADCONTEXT_HANDLE)EncodePointer(contextInfo);
#if defined(_CONTROL_FLOW_GUARD)
if (!PHASE_OFF1(Js::PreReservedHeapAllocPhase))
{
*prereservedRegionAddr = (intptr_t)contextInfo->GetPreReservedSectionAllocator()->EnsurePreReservedRegion();
contextInfo->SetCanCreatePreReservedSegment(*prereservedRegionAddr != 0);
}
#if !defined(_M_ARM)
*jitThunkAddr = (intptr_t)contextInfo->GetJITThunkEmitter()->EnsureInitialized();
#endif
#endif
return hr;
});
}
HRESULT
ServerInitializeScriptContext(
/* [in] */ handle_t binding,
/* [in] */ __RPC__in ScriptContextDataIDL * scriptContextData,
/* [in] */ __RPC__in PTHREADCONTEXT_HANDLE threadContextInfoAddress,
/* [out] */ __RPC__deref_out_opt PPSCRIPTCONTEXT_HANDLE scriptContextInfoAddress)
{
if (scriptContextInfoAddress == nullptr || threadContextInfoAddress == nullptr)
{
Assert(false);
return RPC_S_INVALID_ARG;
}
*scriptContextInfoAddress = nullptr;
ServerThreadContext * threadContextInfo = (ServerThreadContext*)DecodePointer(threadContextInfoAddress);
return ServerCallWrapper(threadContextInfo, [&]()->HRESULT
{
ServerScriptContext * contextInfo = HeapNew(ServerScriptContext, scriptContextData, threadContextInfo);
ServerContextManager::RegisterScriptContext(contextInfo);
*scriptContextInfoAddress = (PSCRIPTCONTEXT_HANDLE)EncodePointer(contextInfo);
#if !FLOATVAR
// TODO: should move this to ServerInitializeThreadContext, also for the fields in IDL
XProcNumberPageSegmentImpl::Initialize(contextInfo->IsRecyclerVerifyEnabled(), contextInfo->GetRecyclerVerifyPad());
#endif
return S_OK;
});
}
#pragma warning(pop)
HRESULT
ServerCleanupThreadContext(
/* [in] */ handle_t binding,
/* [in] */ __RPC__deref_inout_opt PPTHREADCONTEXT_HANDLE threadContextInfoAddress)
{
if (threadContextInfoAddress == nullptr)
{
Assert(false);
return RPC_S_INVALID_ARG;
}
ServerThreadContext * threadContextInfo = (ServerThreadContext*)DecodePointer(*threadContextInfoAddress);
if (threadContextInfo == nullptr)
{
Assert(false);
return RPC_S_INVALID_ARG;
}
// This tells the run-time, when it is marshalling the out
// parameters, that the context handle has been closed normally.
*threadContextInfoAddress = nullptr;
return ServerCallWrapper(threadContextInfo, [&]()->HRESULT
{
threadContextInfo->Close();
ServerContextManager::UnRegisterThreadContext(threadContextInfo);
return S_OK;
});
}
HRESULT
ServerUpdatePropertyRecordMap(
/* [in] */ handle_t binding,
/* [in] */ __RPC__in PTHREADCONTEXT_HANDLE threadContextInfoAddress,
/* [in] */ __RPC__in_opt BVSparseNodeIDL * updatedPropsBVHead)
{
ServerThreadContext * threadContextInfo = (ServerThreadContext*)DecodePointer(threadContextInfoAddress);
if (threadContextInfo == nullptr)
{
Assert(false);
return RPC_S_INVALID_ARG;
}
return ServerCallWrapper(threadContextInfo, [&]()->HRESULT
{
typedef ServerThreadContext::BVSparseNode BVSparseNode;
CompileAssert(sizeof(BVSparseNode) == sizeof(BVSparseNodeIDL));
threadContextInfo->UpdateNumericPropertyBV((BVSparseNode*)updatedPropsBVHead);
return S_OK;
});
}
HRESULT
ServerAddModuleRecordInfo(
/* [in] */ handle_t binding,
/* [in] */ __RPC__in PSCRIPTCONTEXT_HANDLE scriptContextInfoAddress,
/* [in] */ unsigned int moduleId,
/* [in] */ intptr_t localExportSlotsAddr)
{
ServerScriptContext * serverScriptContext = (ServerScriptContext*)DecodePointer(scriptContextInfoAddress);
if (serverScriptContext == nullptr)
{
Assert(false);
return RPC_S_INVALID_ARG;
}
return ServerCallWrapper(serverScriptContext, [&]()->HRESULT
{
serverScriptContext->AddModuleRecordInfo(moduleId, localExportSlotsAddr);
return S_OK;
});
}
HRESULT
ServerSetWellKnownHostTypeId(
/* [in] */ handle_t binding,
/* [in] */ __RPC__in PTHREADCONTEXT_HANDLE threadContextInfoAddress,
/* [in] */ int typeId)
{
ServerThreadContext * threadContextInfo = (ServerThreadContext*)DecodePointer(threadContextInfoAddress);
if (threadContextInfo == nullptr)
{
Assert(false);
return RPC_S_INVALID_ARG;
}
return ServerCallWrapper(threadContextInfo, [&]()->HRESULT
{
threadContextInfo->SetWellKnownHostTypeId((Js::TypeId)typeId);
return S_OK;
});
}
HRESULT
ServerCleanupScriptContext(
/* [in] */ handle_t binding,
/* [in] */ __RPC__deref_inout_opt PPSCRIPTCONTEXT_HANDLE scriptContextInfoAddress)
{
if (scriptContextInfoAddress == nullptr)
{
Assert(false);
return RPC_S_INVALID_ARG;
}
ServerScriptContext * scriptContextInfo = (ServerScriptContext*)DecodePointer(*scriptContextInfoAddress);
if (scriptContextInfo == nullptr)
{
Assert(false);
return RPC_S_INVALID_ARG;
}
if (!scriptContextInfo->IsClosed())
{
scriptContextInfo->Close();
ServerContextManager::UnRegisterScriptContext(scriptContextInfo);
}
// This tells the run-time, when it is marshalling the out
// parameters, that the context handle has been closed normally.
*scriptContextInfoAddress = nullptr;
HeapDelete(scriptContextInfo);
return S_OK;
}
HRESULT
ServerCloseScriptContext(
/* [in] */ handle_t binding,
/* [in] */ __RPC__in PSCRIPTCONTEXT_HANDLE scriptContextInfoAddress)
{
ServerScriptContext * scriptContextInfo = (ServerScriptContext*)DecodePointer(scriptContextInfoAddress);
if (scriptContextInfo == nullptr)
{
Assert(false);
return RPC_S_INVALID_ARG;
}
return ServerCallWrapper(scriptContextInfo, [&]()->HRESULT
{
#ifdef PROFILE_EXEC
scriptContextInfo->GetFirstCodeGenProfiler()->ProfilePrint();
#endif
scriptContextInfo->Close();
ServerContextManager::UnRegisterScriptContext(scriptContextInfo);
return S_OK;
});
}
HRESULT
ServerDecommitInterpreterBufferManager(
/* [in] */ handle_t binding,
/* [in] */ __RPC__in PSCRIPTCONTEXT_HANDLE scriptContextInfoAddress,
/* [in] */ boolean asmJsManager)
{
ServerScriptContext * scriptContext = (ServerScriptContext *)DecodePointer((void*)scriptContextInfoAddress);
if (scriptContext == nullptr)
{
Assert(false);
return RPC_S_INVALID_ARG;
}
return ServerCallWrapper(scriptContext, [&]()->HRESULT
{
scriptContext->DecommitEmitBufferManager(asmJsManager != FALSE);
return S_OK;
});
}
HRESULT
ServerNewInterpreterThunkBlock(
/* [in] */ handle_t binding,
/* [in] */ __RPC__in PSCRIPTCONTEXT_HANDLE scriptContextInfo,
/* [in] */ __RPC__in InterpreterThunkInputIDL * thunkInput,
/* [out] */ __RPC__out InterpreterThunkOutputIDL * thunkOutput)
{
memset(thunkOutput, 0, sizeof(InterpreterThunkOutputIDL));
ServerScriptContext * scriptContext = (ServerScriptContext *)DecodePointer(scriptContextInfo);
if (scriptContext == nullptr)
{
Assert(false);
return RPC_S_INVALID_ARG;
}
return ServerCallWrapper(scriptContext, [&]()->HRESULT
{
ServerThreadContext * threadContext = scriptContext->GetThreadContext();
class AutoLocalAlloc
{
public:
AutoLocalAlloc(ServerThreadContext * threadContext) : localAddress(nullptr), threadContext(threadContext) { }
~AutoLocalAlloc()
{
if (localAddress)
{
threadContext->GetCodePageAllocators()->FreeLocal(this->localAddress, this->segment);
}
}
char * localAddress;
void * segment;
ServerThreadContext * threadContext;
} localAlloc(threadContext);
OOPEmitBufferManagerWithLock * emitBufferManager = scriptContext->GetEmitBufferManager(thunkInput->asmJsThunk != FALSE);
BYTE* runtimeAddress;
EmitBufferAllocation<SectionAllocWrapper, PreReservedSectionAllocWrapper> * alloc = emitBufferManager->AllocateBuffer(InterpreterThunkEmitter::BlockSize, &runtimeAddress);
CompileAssert(InterpreterThunkEmitter::BlockSize <= CustomHeap::Page::MaxAllocationSize);
localAlloc.segment = alloc->allocation->page->segment;
localAlloc.localAddress = threadContext->GetCodePageAllocators()->AllocLocal((char*)runtimeAddress, InterpreterThunkEmitter::BlockSize, localAlloc.segment);
if (!localAlloc.localAddress)
{
Js::Throw::OutOfMemory();
}
#if PDATA_ENABLED
PRUNTIME_FUNCTION pdataStart = {0};
intptr_t epilogEnd = 0;
#endif
DWORD thunkCount = 0;
InterpreterThunkEmitter::FillBuffer(
threadContext,
thunkInput->asmJsThunk != FALSE,
(intptr_t)runtimeAddress,
InterpreterThunkEmitter::BlockSize,
(BYTE*)localAlloc.localAddress,
#if PDATA_ENABLED
&pdataStart,
&epilogEnd,
#endif
&thunkCount
);
if (!emitBufferManager->CommitBufferForInterpreter(alloc, runtimeAddress, InterpreterThunkEmitter::BlockSize))
{
Js::Throw::OutOfMemory();
}
// Call to set VALID flag for CFG check
if (CONFIG_FLAG(OOPCFGRegistration))
{
emitBufferManager->SetValidCallTarget(alloc, runtimeAddress, true);
}
thunkOutput->thunkCount = thunkCount;
thunkOutput->mappedBaseAddr = (intptr_t)runtimeAddress;
#if PDATA_ENABLED
thunkOutput->pdataTableStart = (intptr_t)pdataStart;
thunkOutput->epilogEndAddr = epilogEnd;
#endif
return S_OK;
});
}
#if DBG
HRESULT
ServerIsInterpreterThunkAddr(
/* [in] */ handle_t binding,
/* [in] */ __RPC__in PSCRIPTCONTEXT_HANDLE scriptContextInfoAddress,
/* [in] */ intptr_t address,
/* [in] */ boolean asmjsThunk,
/* [out] */ __RPC__out boolean * result)
{
ServerScriptContext * context = (ServerScriptContext*)DecodePointer((void*)scriptContextInfoAddress);
if (context == nullptr)
{
*result = false;
return RPC_S_INVALID_ARG;
}
OOPEmitBufferManagerWithLock * manager = context->GetEmitBufferManager(asmjsThunk != FALSE);
if (manager == nullptr)
{
*result = false;
return S_OK;
}
*result = manager->IsInHeap((void*)address);
return S_OK;
}
#endif
HRESULT
ServerFreeAllocation(
/* [in] */ handle_t binding,
/* [in] */ __RPC__in PSCRIPTCONTEXT_HANDLE scriptContextInfo,
/* [in] */ intptr_t codeAddress)
{
ServerScriptContext* context = (ServerScriptContext*)DecodePointer(scriptContextInfo);
if (context == nullptr)
{
Assert(false);
return RPC_S_INVALID_ARG;
}
return ServerCallWrapper(context, [&]()->HRESULT
{
context->GetCodeGenAllocators()->emitBufferManager.FreeAllocation((void*)codeAddress);
return S_OK;
});
}
HRESULT
ServerIsNativeAddr(
/* [in] */ handle_t binding,
/* [in] */ __RPC__in PTHREADCONTEXT_HANDLE threadContextInfo,
/* [in] */ intptr_t address,
/* [out] */ __RPC__out boolean * result)
{
if (result == nullptr)
{
Assert(false);
return RPC_S_INVALID_ARG;
}
*result = false;
ServerThreadContext* context = (ServerThreadContext*)DecodePointer(threadContextInfo);
if (context == nullptr)
{
Assert(false);
return RPC_S_INVALID_ARG;
}
return ServerCallWrapper(context, [&]()->HRESULT
{
PreReservedSectionAllocWrapper *preReservedAllocWrapper = context->GetPreReservedSectionAllocator();
if (preReservedAllocWrapper->IsInRange((void*)address))
{
*result = true;
}
else if (!context->IsAllJITCodeInPreReservedRegion())
{
AutoCriticalSection autoLock(&context->GetCodePageAllocators()->cs);
*result = context->GetCodePageAllocators()->IsInNonPreReservedPageAllocator((void*)address);
}
else
{
*result = false;
}
return S_OK;
});
}
HRESULT
ServerSetIsPRNGSeeded(
/* [in] */ handle_t binding,
/* [in] */ __RPC__in PSCRIPTCONTEXT_HANDLE scriptContextInfoAddress,
/* [in] */ boolean value)
{
ServerScriptContext * scriptContextInfo = (ServerScriptContext*)DecodePointer(scriptContextInfoAddress);
if (scriptContextInfo == nullptr)
{
Assert(false);
return RPC_S_INVALID_ARG;
}
return ServerCallWrapper(scriptContextInfo, [&]()->HRESULT
{
scriptContextInfo->SetIsPRNGSeeded(value != FALSE);
return S_OK;
});
}
HRESULT
ServerRemoteCodeGen(
/* [in] */ handle_t binding,
/* [in] */ __RPC__in PSCRIPTCONTEXT_HANDLE scriptContextInfoAddress,
/* [in] */ __RPC__in CodeGenWorkItemIDL *workItemData,
/* [out] */ __RPC__out JITOutputIDL *jitData)
{
memset(jitData, 0, sizeof(JITOutputIDL));
ServerScriptContext * scriptContextInfo = (ServerScriptContext*)DecodePointer(scriptContextInfoAddress);
if (scriptContextInfo == nullptr)
{
Assert(false);
return RPC_S_INVALID_ARG;
}
#if DBG
size_t serializedRpcDataSize = 0;
const unsigned char* serializedRpcData = nullptr;
JITManager::SerializeRPCData(workItemData, &serializedRpcDataSize, &serializedRpcData);
struct AutoFreeArray
{
const byte* arr = nullptr;
size_t bufferSize = 0;
~AutoFreeArray() { HeapDeleteArray(bufferSize, arr); }
} autoFreeArray;
autoFreeArray.arr = serializedRpcData;
autoFreeArray.bufferSize = serializedRpcDataSize;
#endif
return ServerCallWrapper(scriptContextInfo, [&]() ->HRESULT
{
LARGE_INTEGER start_time = { 0 };
if (PHASE_TRACE1(Js::BackEndPhase))
{
QueryPerformanceCounter(&start_time);
}
scriptContextInfo->UpdateGlobalObjectThisAddr(workItemData->globalThisAddr);
ServerThreadContext * threadContextInfo = scriptContextInfo->GetThreadContext();
AutoReturnPageAllocator autoReturnPageAllocator;
PageAllocator* pageAllocator = autoReturnPageAllocator.GetPageAllocator();
NoRecoverMemoryJitArenaAllocator jitArena(L"JITArena", pageAllocator, Js::Throw::OutOfMemory);
#if DBG
jitArena.SetNeedsDelayFreeList();
#endif
JITTimeWorkItem * jitWorkItem = Anew(&jitArena, JITTimeWorkItem, workItemData);
if (PHASE_VERBOSE_TRACE_RAW(Js::BackEndPhase, jitWorkItem->GetJITTimeInfo()->GetSourceContextId(), jitWorkItem->GetJITTimeInfo()->GetLocalFunctionId()))
{
LARGE_INTEGER freq;
LARGE_INTEGER end_time;
QueryPerformanceCounter(&end_time);
QueryPerformanceFrequency(&freq);
Output::Print(
L"BackendMarshalIn - function: %s time:%8.6f mSec\r\n",
jitWorkItem->GetJITFunctionBody()->GetDisplayName(),
(((double)((end_time.QuadPart - workItemData->startTime)* (double)1000.0 / (double)freq.QuadPart))) / (1));
Output::Flush();
}
#ifdef PROFILE_EXEC
Js::ScriptContextProfiler* profiler = scriptContextInfo->GetCodeGenProfiler(pageAllocator);
#else
Js::ScriptContextProfiler* profiler = nullptr;
#endif
#if !FLOATVAR
if (jitWorkItem->GetWorkItemData()->xProcNumberPageSegment)
{
jitData->numberPageSegments = (XProcNumberPageSegment*)midl_user_allocate(sizeof(XProcNumberPageSegment));
if (!jitData->numberPageSegments)
{
return E_OUTOFMEMORY;
}
__analysis_assume(jitData->numberPageSegments);
memcpy_s(jitData->numberPageSegments, sizeof(XProcNumberPageSegment), jitWorkItem->GetWorkItemData()->xProcNumberPageSegment, sizeof(XProcNumberPageSegment));
}
#endif
Func::Codegen(
&jitArena,
jitWorkItem,
threadContextInfo,
scriptContextInfo,
jitData,
nullptr,
nullptr,
jitWorkItem->GetPolymorphicInlineCacheInfo(),
scriptContextInfo->GetCodeGenAllocators(),
#if !FLOATVAR
nullptr, // number allocator
#endif
profiler,
true);
#ifdef PROFILE_EXEC
if (profiler && profiler->IsInitialized())
{
profiler->ProfilePrint(Js::Configuration::Global.flags.Profile.GetFirstPhase());
}
#endif
if (PHASE_VERBOSE_TRACE_RAW(Js::BackEndPhase, jitWorkItem->GetJITTimeInfo()->GetSourceContextId(), jitWorkItem->GetJITTimeInfo()->GetLocalFunctionId()))
{
LARGE_INTEGER freq;
LARGE_INTEGER end_time;
QueryPerformanceCounter(&end_time);
QueryPerformanceFrequency(&freq);
Output::Print(
L"EndBackEndInner - function: %s time:%8.6f mSec\r\n",
jitWorkItem->GetJITFunctionBody()->GetDisplayName(),
(((double)((end_time.QuadPart - start_time.QuadPart)* (double)1000.0 / (double)freq.QuadPart))) / (1));
Output::Flush();
}
LARGE_INTEGER out_time = { 0 };
if (PHASE_TRACE1(Js::BackEndPhase))
{
QueryPerformanceCounter(&out_time);
jitData->startTime = out_time.QuadPart;
}
Assert(jitData->codeAddress);
Assert(jitData->codeSize);
return S_OK;
});
}
JsUtil::BaseHashSet<ServerThreadContext*, HeapAllocator> ServerContextManager::threadContexts(&HeapAllocator::Instance);
JsUtil::BaseHashSet<ServerScriptContext*, HeapAllocator> ServerContextManager::scriptContexts(&HeapAllocator::Instance);
CriticalSection ServerContextManager::cs;
BaseDictionary<DWORD, ProcessContext*, HeapAllocator> ProcessContextManager::ProcessContexts(&HeapAllocator::Instance);
CriticalSection ProcessContextManager::cs;
HRESULT
ProcessContextManager::RegisterNewProcess(DWORD pid, HANDLE processHandle, intptr_t chakraBaseAddress, intptr_t crtBaseAddress)
{
AutoCriticalSection autoCS(&cs);
for (auto iter = ProcessContexts.GetIteratorWithRemovalSupport(); iter.IsValid(); iter.MoveNext())
{
ProcessContext* context = iter.CurrentValue();
// We can delete a ProcessContext if no ThreadContexts refer to it and the process is terminated
if (!context->HasRef() && WaitForSingleObject(context->processHandle, 0) == WAIT_OBJECT_0)
{
iter.RemoveCurrent();
HeapDelete(context);
}
}
// We cannot register multiple ProcessContexts for a single process
if (ProcessContexts.ContainsKey(pid))
{
Assert(UNREACHED);
return E_ACCESSDENIED;
}
ProcessContext* context = nullptr;
try
{
AUTO_NESTED_HANDLED_EXCEPTION_TYPE(static_cast<ExceptionType>(ExceptionType_OutOfMemory));
context = HeapNew(ProcessContext, processHandle, chakraBaseAddress, crtBaseAddress);
ProcessContexts.Add(pid, context);
}
catch (Js::OutOfMemoryException)
{
if (context != nullptr)
{
// If we OOM while registering the ProcessContext, we should free it
HeapDelete(context);
}
return E_OUTOFMEMORY;
}
return S_OK;
}
ProcessContext*
ProcessContextManager::GetProcessContext(DWORD pid)
{
AutoCriticalSection autoCS(&cs);
ProcessContext* context = nullptr;
// It is possible that we don't have a ProcessContext for a pid in case ProcessContext initialization failed,
// or if the calling process terminated and the ProcessContext was already cleaned up before we got here
if (ProcessContexts.ContainsKey(pid))
{
context = ProcessContexts.Item(pid);
context->AddRef();
}
return context;
}
#ifdef STACK_BACK_TRACE
SList<ServerContextManager::ClosedContextEntry<ServerThreadContext>*, NoThrowHeapAllocator> ServerContextManager::ClosedThreadContextList(&NoThrowHeapAllocator::Instance);
SList<ServerContextManager::ClosedContextEntry<ServerScriptContext>*, NoThrowHeapAllocator> ServerContextManager::ClosedScriptContextList(&NoThrowHeapAllocator::Instance);
#endif
void ServerContextManager::RegisterThreadContext(ServerThreadContext* threadContext)
{
AutoCriticalSection autoCS(&cs);
threadContexts.Add(threadContext);
}
void ServerContextManager::UnRegisterThreadContext(ServerThreadContext* threadContext)
{
AutoCriticalSection autoCS(&cs);
threadContexts.Remove(threadContext);
auto iter = scriptContexts.GetIteratorWithRemovalSupport();
while (iter.IsValid())
{
ServerScriptContext* scriptContext = iter.Current().Key();
if (scriptContext->GetThreadContext() == threadContext)
{
if (!scriptContext->IsClosed())
{
scriptContext->Close();
}
iter.RemoveCurrent();
}
iter.MoveNext();
}
}
void ServerContextManager::RegisterScriptContext(ServerScriptContext* scriptContext)
{
AutoCriticalSection autoCS(&cs);
scriptContexts.Add(scriptContext);
}
void ServerContextManager::UnRegisterScriptContext(ServerScriptContext* scriptContext)
{
AutoCriticalSection autoCS(&cs);
scriptContexts.Remove(scriptContext);
}
bool ServerContextManager::CheckLivenessAndAddref(ServerScriptContext* context)
{
AutoCriticalSection autoCS(&cs);
if (scriptContexts.LookupWithKey(context))
{
if (!context->IsClosed() && !context->GetThreadContext()->IsClosed())
{
context->AddRef();
context->GetThreadContext()->AddRef();
return true;
}
}
return false;
}
bool ServerContextManager::CheckLivenessAndAddref(ServerThreadContext* context)
{
AutoCriticalSection autoCS(&cs);
if (threadContexts.LookupWithKey(context))
{
if (!context->IsClosed())
{
context->AddRef();
return true;
}
}
return false;
}
template<typename Fn>
HRESULT ServerCallWrapper(ServerThreadContext* threadContextInfo, Fn fn)
{
MemoryOperationLastError::ClearLastError();
HRESULT hr = S_OK;
try
{
AUTO_NESTED_HANDLED_EXCEPTION_TYPE(static_cast<ExceptionType>(ExceptionType_OutOfMemory | ExceptionType_StackOverflow));
AutoReleaseThreadContext autoThreadContext(threadContextInfo);
hr = fn();
}
catch (ContextClosedException&)
{
hr = E_ACCESSDENIED;
}
catch (Js::OutOfMemoryException)
{
hr = E_OUTOFMEMORY;
}
catch (Js::StackOverflowException)
{
hr = VBSERR_OutOfStack;
}
catch (Js::OperationAbortedException)
{
hr = E_ABORT;
}
catch (...)
{
AssertOrFailFastMsg(false, "Unknown exception caught in JIT server call.");
}
if (hr == S_OK)
{
return MemoryOperationLastError::GetLastError();
}
return hr;
}
template<typename Fn>
HRESULT ServerCallWrapper(ServerScriptContext* scriptContextInfo, Fn fn)
{
try
{
AutoReleaseScriptContext autoScriptContext(scriptContextInfo);
ServerThreadContext* threadContextInfo = scriptContextInfo->GetThreadContext();
return ServerCallWrapper(threadContextInfo, fn);
}
catch (ContextClosedException&)
{
return E_ACCESSDENIED;
}
}