-
Notifications
You must be signed in to change notification settings - Fork 0
/
plv8.cc
2457 lines (2145 loc) · 67.3 KB
/
plv8.cc
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
994
995
996
997
998
999
1000
/*-------------------------------------------------------------------------
*
* plv8.cc : PL/v8 handler routines.
*
* Copyright (c) 2009-2012, the PLV8JS Development Group.
*-------------------------------------------------------------------------
*/
#include "plv8.h"
#ifdef _MSC_VER
#undef open
#endif
#include "libplatform/libplatform.h"
#include "plv8_allocator.h"
#include <new>
extern "C" {
#if PG_VERSION_NUM >= 90300
#include "access/htup_details.h"
#endif
#include "access/xact.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "commands/trigger.h"
#include "executor/spi.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#if PG_VERSION_NUM >= 120000
#include "catalog/pg_database.h"
#endif
#if PG_VERSION_NUM >= 130000
#include "common/hashfn.h"
#endif
#include <signal.h>
#ifdef EXECUTION_TIMEOUT
#ifdef _MSC_VER
#include <windows.h>
#else
#include <unistd.h>
#endif
#endif
PG_MODULE_MAGIC;
PGDLLEXPORT Datum plv8_call_handler(PG_FUNCTION_ARGS);
PGDLLEXPORT Datum plv8_call_validator(PG_FUNCTION_ARGS);
PGDLLEXPORT Datum plcoffee_call_handler(PG_FUNCTION_ARGS);
PGDLLEXPORT Datum plcoffee_call_validator(PG_FUNCTION_ARGS);
PGDLLEXPORT Datum plls_call_handler(PG_FUNCTION_ARGS);
PGDLLEXPORT Datum plls_call_validator(PG_FUNCTION_ARGS);
PGDLLEXPORT Datum plv8_reset(PG_FUNCTION_ARGS);
PGDLLEXPORT Datum plv8_info(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(plv8_call_handler);
PG_FUNCTION_INFO_V1(plv8_call_validator);
PG_FUNCTION_INFO_V1(plcoffee_call_handler);
PG_FUNCTION_INFO_V1(plcoffee_call_validator);
PG_FUNCTION_INFO_V1(plls_call_handler);
PG_FUNCTION_INFO_V1(plls_call_validator);
PG_FUNCTION_INFO_V1(plv8_reset);
PG_FUNCTION_INFO_V1(plv8_info);
PGDLLEXPORT void _PG_init(void);
#if PG_VERSION_NUM >= 90000
PGDLLEXPORT Datum plv8_inline_handler(PG_FUNCTION_ARGS);
PGDLLEXPORT Datum plcoffee_inline_handler(PG_FUNCTION_ARGS);
PGDLLEXPORT Datum plls_inline_handler(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(plv8_inline_handler);
PG_FUNCTION_INFO_V1(plcoffee_inline_handler);
PG_FUNCTION_INFO_V1(plls_inline_handler);
#endif
} // extern "C"
using namespace v8;
typedef struct plv8_proc_cache
{
Oid fn_oid;
Persistent<Function> function;
char proname[NAMEDATALEN];
char *prosrc;
TransactionId fn_xmin;
ItemPointerData fn_tid;
Oid user_id;
int nargs;
bool retset; /* true if SRF */
Oid rettype;
Oid argtypes[FUNC_MAX_ARGS];
} plv8_proc_cache;
plv8_context *current_context = nullptr;
size_t plv8_memory_limit = 0;
size_t plv8_last_heap_size = 0;
/*
* The function and context are created at the first invocation. Their
* lifetime is same as plv8_proc, but they are not palloc'ed memory,
* so we need to clear them at the end of transaction.
*/
typedef struct plv8_exec_env
{
Isolate *isolate;
Persistent<Object> recv;
Persistent<Context> context;
Local<Context> localContext() { return Local<Context>::New(isolate, context) ; }
struct plv8_exec_env *next;
} plv8_exec_env;
/*
* We cannot cache plv8_type inter executions because it has FmgrInfo fields.
* So, we cache rettype and argtype in fn_extra only during one execution.
*/
typedef struct plv8_proc
{
plv8_proc_cache *cache;
plv8_exec_env *xenv;
TypeFuncClass functypclass; /* For SRF */
plv8_type rettype;
plv8_type argtypes[FUNC_MAX_ARGS];
} plv8_proc;
static HTAB *plv8_proc_cache_hash = NULL;
static plv8_exec_env *exec_env_head = NULL;
extern const unsigned char coffee_script_binary_data[];
extern const unsigned char livescript_binary_data[];
static void killPlv8Context(plv8_context *ctx);
/*
* lower_case_functions are postgres-like C functions.
* They could raise errors with elog/ereport(ERROR).
*/
static plv8_proc *plv8_get_proc(Oid fn_oid, FunctionCallInfo fcinfo,
bool validate, char ***argnames) throw();
static void plv8_xact_cb(XactEvent event, void *arg);
/*
* CamelCaseFunctions are C++ functions.
* They could raise errors with C++ throw statements, or never throw exceptions.
*/
static plv8_exec_env *CreateExecEnv(Handle<Function> function, plv8_context *context);
static plv8_exec_env *CreateExecEnv(Persistent<Function>& function, plv8_context *context);
static plv8_proc *Compile(Oid fn_oid, FunctionCallInfo fcinfo,
bool validate, bool is_trigger, Dialect dialect);
static Local<Function> CompileFunction(plv8_context *global_context,
const char *proname, int proarglen,
const char *proargs[], const char *prosrc,
bool is_trigger, bool retset, Dialect dialect);
static Datum CallFunction(PG_FUNCTION_ARGS, plv8_exec_env *xenv,
int nargs, plv8_type argtypes[], plv8_type *rettype);
static Datum CallSRFunction(PG_FUNCTION_ARGS, plv8_exec_env *xenv,
int nargs, plv8_type argtypes[], plv8_type *rettype);
static Datum CallTrigger(PG_FUNCTION_ARGS, plv8_exec_env *xenv);
static plv8_context *GetPlv8Context();
static Local<ObjectTemplate> GetGlobalObjectTemplate(Isolate *isolate);
static void CreateIsolate(plv8_context *context);
/* A GUC to specify a custom start up function to call */
static char *plv8_start_proc = NULL;
/* A GUC to specify V8 flags (e.g. --es_staging) */
static char *plv8_v8_flags = NULL;
/* A GUC to specify the ICU data directory */
static char *plv8_icu_data = NULL;
/* A GUC to specify the remote debugger port */
static int plv8_debugger_port;
#ifdef EXECUTION_TIMEOUT
static int plv8_execution_timeout = 300;
#endif
static std::unique_ptr<v8::Platform> v8_platform = NULL;
/*
* We use vector instead of hash since the size of this array
* is expected to be short in most cases.
*/
static std::vector<plv8_context *> ContextVector;
#ifdef ENABLE_DEBUGGER_SUPPORT
v8::Persistent<v8::Context> debug_message_context;
void DispatchDebugMessages() {
// We are in some random thread. We should already have v8::Locker acquired
// (we requested this when registered this callback). We was called
// because new debug messages arrived; they may have already been processed,
// but we shouldn't worry about this.
//
// All we have to do is to set context and call ProcessDebugMessages.
//
// We should decide which V8 context to use here. This is important for
// "evaluate" command, because it must be executed some context.
// In our sample we have only one context, so there is nothing really to
// think about.
v8::Context::Scope scope(debug_message_context);
v8::Debug::ProcessDebugMessages();
}
#endif // ENABLE_DEBUGGER_SUPPORT
void OOMErrorHandler(const char* location, bool is_heap_oom) {
Isolate *isolate = Isolate::GetCurrent();
isolate->TerminateExecution();
// set it to kill the user context and isolate
current_context->is_dead = true;
elog(ERROR, "Out of memory error");
}
void GCEpilogueCallback(Isolate* isolate, GCType type, GCCallbackFlags /* flags */) {
HeapStatistics heap_statistics;
isolate->GetHeapStatistics(&heap_statistics);
//elog(NOTICE, "Current memory: %lld => %lld", heap_statistics.used_heap_size(), plv8_memory_limit * 1_MB);
if (type != GCType::kGCTypeIncrementalMarking
&& heap_statistics.used_heap_size() > plv8_memory_limit * 1_MB) {
//elog(NOTICE, "Terminating");
const char *error_message = "Out of memory";
Local<String> result = ToString(error_message, 13);
isolate->ThrowException(result);
//isolate->setData(MEM_SOFTLIMIT_REACHED);
isolate->TerminateExecution();
}
if (heap_statistics.used_heap_size() > plv8_memory_limit * 1_MB / 0.9
&& plv8_last_heap_size < plv8_memory_limit * 1_MB / 0.9) {
isolate->LowMemoryNotification();
}
plv8_last_heap_size = heap_statistics.used_heap_size();
}
size_t NearHeapLimitHandler(void* data, size_t current_heap_limit,
size_t initial_heap_limit) {
Isolate *isolate = Isolate::GetCurrent();
isolate->TerminateExecution();
// need to give back more space
// to make sure it can unwind the stack and process exceptions
return current_heap_limit + 1_MB;
}
void PromiseRejectCB(PromiseRejectMessage rejection) {
auto event = rejection.GetEvent();
if (event == kPromiseRejectAfterResolved || event == kPromiseResolveAfterResolved)
return;
auto promise = rejection.GetPromise();
auto isolate = promise->GetIsolate();
if (rejection.GetEvent() == v8::kPromiseHandlerAddedAfterReject) {
if (current_context->ignore_unhandled_promises) return;
// Remove handled promises from the list
auto& unhandled_promises = current_context->unhandled_promises;
for (auto it = unhandled_promises.begin(); it != unhandled_promises.end(); ++it) {
auto unhandled_promise = std::get<0>(*it).Get(isolate);
if (unhandled_promise == promise) {
unhandled_promises.erase(it--);
}
}
return;
}
auto exception = rejection.GetValue();
Local<Message> message;
// Assume that all objects are stack-traces.
if (exception->IsObject()) {
message = Exception::CreateMessage(isolate, exception);
}
if (!exception->IsNativeError() &&
(message.IsEmpty() || message->GetStackTrace().IsEmpty())) {
// If there is no real Error object, manually throw and catch a stack trace.
TryCatch try_catch(isolate);
try_catch.SetVerbose(true);
isolate->ThrowException(Exception::Error(
String::NewFromUtf8Literal(isolate, "Unhandled Promise.")));
message = try_catch.Message();
exception = try_catch.Exception();
}
if (current_context->ignore_unhandled_promises) return;
current_context->unhandled_promises.emplace_back(
v8::Global<v8::Promise>(isolate, promise),
v8::Global<v8::Message>(isolate, message),
v8::Global<v8::Value>(isolate, exception));
}
void HandleUnhandledPromiseRejections() {
// Avoid recursive calls to HandleUnhandledPromiseRejections.
auto isolate = current_context->isolate;
if (current_context->ignore_unhandled_promises) return;
current_context->ignore_unhandled_promises = true;
HandleScope scope(isolate);
// Ignore promises that get added during error reporting.
size_t i = 0;
auto& unhandled_promises = current_context->unhandled_promises;
for (; i < unhandled_promises.size(); i++) {
const auto& tuple = unhandled_promises[i];
Local<v8::Message> message = std::get<1>(tuple).Get(isolate);
Local<v8::Value> exception = std::get<2>(tuple).Get(isolate);
js_error error(isolate, exception, message);
error.log(WARNING, "Unhandled Promise rejection: %s");
}
unhandled_promises.clear();
current_context->ignore_unhandled_promises = false;
}
static void
CreateIsolate(plv8_context *context) {
Isolate *isolate;
Isolate::CreateParams params;
params.array_buffer_allocator = new ArrayAllocator(plv8_memory_limit * 1_MB);
//params.array_buffer_allocator =
// v8::ArrayBuffer::Allocator::NewDefaultAllocator();
ResourceConstraints rc;
rc.ConfigureDefaults(plv8_memory_limit * 1_MB * 2, plv8_memory_limit * 1_MB * 2);
params.constraints = rc;
isolate = Isolate::New(params);
isolate->SetOOMErrorHandler(OOMErrorHandler);
isolate->AddGCEpilogueCallback(GCEpilogueCallback);
isolate->AddNearHeapLimitCallback(NearHeapLimitHandler, NULL);
isolate->SetPromiseRejectCallback(PromiseRejectCB);
context->isolate = isolate;
context->array_buffer_allocator = params.array_buffer_allocator;
}
void
_PG_init(void)
{
HASHCTL hash_ctl = { 0 };
hash_ctl.keysize = sizeof(Oid);
hash_ctl.entrysize = sizeof(plv8_proc_cache);
hash_ctl.hash = oid_hash;
plv8_proc_cache_hash = hash_create("PLv8 Procedures", 32,
&hash_ctl, HASH_ELEM | HASH_FUNCTION);
DefineCustomStringVariable("plv8.start_proc",
gettext_noop("PLV8 function to run once when PLV8 is first used."),
NULL,
&plv8_start_proc,
NULL,
PGC_USERSET, 0,
#if PG_VERSION_NUM >= 90100
NULL,
#endif
NULL,
NULL);
DefineCustomStringVariable("plv8.icu_data",
gettext_noop("ICU data file directory."),
NULL,
&plv8_icu_data,
NULL,
PGC_USERSET, 0,
#if PG_VERSION_NUM >= 90100
NULL,
#endif
NULL,
NULL);
DefineCustomStringVariable("plv8.v8_flags",
gettext_noop("V8 engine initialization flags (e.g. --harmony for all current harmony features)."),
NULL,
&plv8_v8_flags,
NULL,
PGC_USERSET, 0,
#if PG_VERSION_NUM >= 90100
NULL,
#endif
NULL,
NULL);
DefineCustomIntVariable("plv8.debugger_port",
gettext_noop("V8 remote debug port."),
gettext_noop("The default value is 35432. "
"This is effective only if PLV8 is built with ENABLE_DEBUGGER_SUPPORT."),
&plv8_debugger_port,
35432, 0, 65536,
PGC_USERSET, 0,
#if PG_VERSION_NUM >= 90100
NULL,
#endif
NULL,
NULL);
#ifdef EXECUTION_TIMEOUT
DefineCustomIntVariable("plv8.execution_timeout",
gettext_noop("V8 execution timeout."),
gettext_noop("The default value is 300 seconds. "
"This allows you to override the default execution timeout."),
&plv8_execution_timeout,
300, 1, 65536,
PGC_USERSET, 0,
#if PG_VERSION_NUM >= 90100
NULL,
#endif
NULL,
NULL);
#endif
DefineCustomIntVariable("plv8.memory_limit",
gettext_noop("Per-isolate memory limit in MBytes"),
gettext_noop("The default value is 256 MB"),
(int*)&plv8_memory_limit,
256, 256, 3096, // hardcoded v8 limits for isolates
PGC_SUSET, 0,
#if PG_VERSION_NUM >= 90100
NULL,
#endif
NULL,
NULL);
RegisterXactCallback(plv8_xact_cb, NULL);
EmitWarningsOnPlaceholders("plv8");
if (plv8_icu_data == NULL) {
elog(DEBUG1, "no icu dir");
V8::InitializeICU();
} else {
elog(DEBUG1, "init icu data %s", plv8_icu_data);
V8::InitializeICU(plv8_icu_data);
}
#if (V8_MAJOR_VERSION == 4 && V8_MINOR_VERSION >= 6) || V8_MAJOR_VERSION >= 5
V8::InitializeExternalStartupData("plv8");
#endif
if (!v8_platform) {
v8_platform = platform::NewDefaultPlatform();
}
V8::InitializePlatform(v8_platform.get());
V8::Initialize();
if (plv8_v8_flags != NULL) {
V8::SetFlagsFromString(plv8_v8_flags, strlen(plv8_v8_flags));
}
}
static void
plv8_xact_cb(XactEvent event, void *arg)
{
plv8_exec_env *env = exec_env_head;
while (env)
{
if (!env->recv.IsEmpty())
{
env->recv.Reset();
}
env = env->next;
/*
* Each item was allocated in TopTransactionContext, so
* it will be freed eventually.
*/
}
exec_env_head = NULL;
}
static inline plv8_exec_env *
plv8_new_exec_env(Isolate *isolate)
{
plv8_exec_env *xenv = (plv8_exec_env *)
MemoryContextAllocZero(TopTransactionContext, sizeof(plv8_exec_env));
new(&xenv->context) Persistent<Context>();
new(&xenv->recv) Persistent<Object>();
xenv->isolate = isolate;
/*
* Add it to the list, which will be freed in the end of top transaction.
*/
xenv->next = exec_env_head;
exec_env_head = xenv;
return xenv;
}
static Datum
common_pl_call_handler(PG_FUNCTION_ARGS, Dialect dialect) throw()
{
current_context = GetPlv8Context();
Oid fn_oid = fcinfo->flinfo->fn_oid;
bool is_trigger = CALLED_AS_TRIGGER(fcinfo);
try
{
#ifdef ENABLE_DEBUGGER_SUPPORT
Locker lock;
#endif // ENABLE_DEBUGGER_SUPPORT
Isolate::Scope scope(current_context->isolate);
HandleScope handle_scope(current_context->isolate);
if (!fcinfo->flinfo->fn_extra)
{
plv8_proc *proc = Compile(fn_oid, fcinfo,
false, is_trigger, dialect);
proc->xenv = CreateExecEnv(proc->cache->function, current_context);
fcinfo->flinfo->fn_extra = proc;
}
plv8_proc *proc = (plv8_proc *) fcinfo->flinfo->fn_extra;
plv8_proc_cache *cache = proc->cache;
if (is_trigger)
return CallTrigger(fcinfo, proc->xenv);
else if (cache->retset)
return CallSRFunction(fcinfo, proc->xenv,
cache->nargs, proc->argtypes, &proc->rettype);
else
return CallFunction(fcinfo, proc->xenv,
cache->nargs, proc->argtypes, &proc->rettype);
}
catch (js_error& e) { e.rethrow(); }
catch (pg_error& e) { e.rethrow(); }
return (Datum) 0; // keep compiler quiet
}
Datum
plv8_call_handler(PG_FUNCTION_ARGS)
{
return common_pl_call_handler(fcinfo, PLV8_DIALECT_NONE);
}
Datum
plcoffee_call_handler(PG_FUNCTION_ARGS)
{
return common_pl_call_handler(fcinfo, PLV8_DIALECT_COFFEE);
}
Datum
plls_call_handler(PG_FUNCTION_ARGS)
{
return common_pl_call_handler(fcinfo, PLV8_DIALECT_LIVESCRIPT);
}
static void killPlv8Context(plv8_context *ctx) {
HASH_SEQ_STATUS status;
plv8_proc_cache* cache;
// need to search and reset all the user functions which were created in the old context
hash_seq_init(&status, plv8_proc_cache_hash);
cache = (plv8_proc_cache *) hash_seq_search(&status);
while (cache != nullptr) {
if (cache->user_id == ctx->user_id) {
if (cache->prosrc)
{
pfree(cache->prosrc);
cache->prosrc = NULL;
}
cache->function.Reset();
}
cache = (plv8_proc_cache *) hash_seq_search(&status);
}
ctx->isolate->Dispose();
delete ctx->array_buffer_allocator;
}
Datum
plv8_reset(PG_FUNCTION_ARGS)
{
Oid user_id = GetUserId();
unsigned long i;
for (i = 0; i < ContextVector.size(); i++)
{
if (ContextVector[i]->user_id == user_id)
{
plv8_context * context = ContextVector[i];
ContextVector.erase(ContextVector.begin() + i);
killPlv8Context(context);
pfree(context);
break;
}
}
return (Datum) 0;
}
Datum
plv8_info(PG_FUNCTION_ARGS)
{
unsigned long i;
unsigned long size = ContextVector.size();
char *infos[size];
size_t lengths[size];
size_t total_length = 3; // length of "[]\0"
for (i = 0; i < size; i++)
{
Isolate *isolate = ContextVector[i]->isolate;
Isolate::Scope scope(isolate);
HandleScope handle_scope(isolate);
Local<Context> context = ContextVector[i]->localContext();
Context::Scope context_scope(context);
JSONObject JSON;
Local<v8::Value> result;
Local<v8::Object> obj = v8::Object::New(isolate);
#if PG_VERSION_NUM >= 90500
char *username = GetUserNameFromId(ContextVector[i]->user_id, false);
#else
char *username = GetUserNameFromId(ContextVector[i]->user_id);
#endif
obj->Set(context, String::NewFromUtf8Literal(isolate, "user"),
String::NewFromUtf8(isolate, username).ToLocalChecked()).Check();
GetMemoryInfo(obj);
result = JSON.Stringify(obj);
CString str(result);
infos[i] = pstrdup(str.str());
lengths[i] = strlen(infos[i]);
total_length += lengths[i] + 1; // add 1 byte for ','
}
char *out = (char *) palloc0(total_length);
out[0] = '[';
size_t current = 0;
for (i = 0; i < size; i++)
{
++current;
strcpy(out + current, infos[i]);
pfree(infos[i]);
current += lengths[i];
out[current] = ',';
}
out[current] = ']';
return CStringGetTextDatum(out);
}
#if PG_VERSION_NUM >= 90000
static Datum
common_pl_inline_handler(PG_FUNCTION_ARGS, Dialect dialect) throw()
{
InlineCodeBlock *codeblock = (InlineCodeBlock *) DatumGetPointer(PG_GETARG_DATUM(0));
Assert(IsA(codeblock, InlineCodeBlock));
try
{
#ifdef ENABLE_DEBUGGER_SUPPORT
Locker lock;
#endif // ENABLE_DEBUGGER_SUPPORT
current_context = GetPlv8Context();
Isolate::Scope scope(current_context->isolate);
HandleScope handle_scope(current_context->isolate);
char *source_text = codeblock->source_text;
Persistent<Context> global_context;
global_context.Reset(current_context->isolate, current_context->context);
Local<Function> function = CompileFunction(current_context,
NULL, 0, NULL,
source_text, false, false, dialect);
plv8_exec_env *xenv = CreateExecEnv(function, current_context);
return CallFunction(fcinfo, xenv, 0, NULL, NULL);
}
catch (js_error& e) { e.rethrow(); }
catch (pg_error& e) { e.rethrow(); }
return (Datum) 0; // keep compiler quiet
}
Datum
plv8_inline_handler(PG_FUNCTION_ARGS)
{
return common_pl_inline_handler(fcinfo, PLV8_DIALECT_NONE);
}
Datum
plcoffee_inline_handler(PG_FUNCTION_ARGS)
{
return common_pl_inline_handler(fcinfo, PLV8_DIALECT_COFFEE);
}
Datum
plls_inline_handler(PG_FUNCTION_ARGS)
{
return common_pl_inline_handler(fcinfo, PLV8_DIALECT_LIVESCRIPT);
}
#endif
#ifdef EXECUTION_TIMEOUT
/*
* Breakout -- break out of a Call, with a thread
*
* This function breaks out of a javascript execution context.
*/
#ifdef _MSC_VER // windows
DWORD WINAPI
Breakout (LPVOID lpParam)
{
Isolate *isolate = (Isolate *) lpParam;
Sleep(plv8_execution_timeout * 1000);
isolate->TerminateExecution();
return 0;
}
#else // posix
void *
Breakout (void *d)
{
auto *isolate = (Isolate *) d;
sleep(plv8_execution_timeout);
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
isolate->TerminateExecution();
return NULL;
}
#endif
#endif
void *int_handler = NULL;
void *term_handler = NULL;
void *abt_handler = NULL;
/*
* signal handler
*
* This function kills the execution of the v8 process if a signal is called
*/
void
signal_handler (int sig) {
elog(DEBUG1, "cancelling execution");
auto running_context = GetPlv8Context();
running_context->interrupted = true;
running_context->isolate->TerminateExecution();
}
/*
* DoCall -- Call a JS function with SPI support.
*
* This function could throw C++ exceptions, but must not throw PG exceptions.
*/
static Local<v8::Value>
DoCall(Local<Context> ctx, Handle<Function> fn, Handle<Object> receiver,
int nargs, Handle<v8::Value> args[], bool nonatomic)
{
Isolate *isolate = ctx->GetIsolate();
TryCatch try_catch(isolate);
if (isolate->IsExecutionTerminating()) {
isolate->CancelTerminateExecution();
}
#if PG_VERSION_NUM >= 110000
if (SPI_connect_ext(nonatomic ? SPI_OPT_NONATOMIC : 0) != SPI_OK_CONNECT)
throw js_error("could not connect to SPI manager");
#else
if (SPI_connect() != SPI_OK_CONNECT)
throw js_error("could not connect to SPI manager");
#endif
// set up the signal handlers
int_handler = (void *) signal(SIGINT, signal_handler);
term_handler = (void *) signal(SIGTERM, signal_handler);
abt_handler = (void *) signal(SIGABRT, signal_handler);
#ifdef EXECUTION_TIMEOUT
bool timeout = false;
#ifdef _MSC_VER // windows
HANDLE hThread;
DWORD dwThreadId;
hThread = CreateThread(NULL, 0, Breakout, isolate, 0, &dwThreadId);
#else
pthread_t breakout_thread;
// set up the thread to break out the execution if needed
pthread_create(&breakout_thread, NULL, Breakout, isolate);
#endif
#endif
try {
MaybeLocal<v8::Value> result = fn->Call(ctx, receiver, nargs, args);
int status = SPI_finish();
#ifdef EXECUTION_TIMEOUT
#ifdef _MSC_VER
if (TerminateThread(hThread, NULL) == 0) {
timeout = true;
}
#else
void *thread_result;
pthread_cancel(breakout_thread);
pthread_join(breakout_thread, &thread_result);
if (thread_result == NULL) {
timeout = true;
}
#endif
#endif
// reset signal handlers
signal(SIGINT, (void (*)(int)) int_handler);
signal(SIGTERM, (void (*)(int)) term_handler);
signal(SIGABRT, (void (*)(int)) abt_handler);
HandleUnhandledPromiseRejections();
if (result.IsEmpty()) {
if (isolate->IsExecutionTerminating()) {
isolate->CancelTerminateExecution();
if (current_context->interrupted) {
current_context->interrupted = false;
throw js_error("Signal caught: interrupted");
}
#ifdef EXECUTION_TIMEOUT
if (timeout) {
throw js_error("execution timeout exceeded");
}
#endif
throw js_error("Out of memory error");
}
throw js_error(try_catch);
}
if (status < 0)
throw js_error(FormatSPIStatus(status));
return result.ToLocalChecked();
} catch (int err) {
elog(NOTICE, "Error caught");
}
}
static Datum
CallFunction(PG_FUNCTION_ARGS, plv8_exec_env *xenv,
int nargs, plv8_type argtypes[], plv8_type *rettype)
{
Local<Context> context = xenv->localContext();
Context::Scope context_scope(context);
Handle<v8::Value> args[FUNC_MAX_ARGS];
Handle<Object> plv8obj;
#if PG_VERSION_NUM >= 110000
bool nonatomic = fcinfo->context &&
IsA(fcinfo->context, CallContext) &&
!castNode(CallContext, fcinfo->context)->atomic;
#else
bool nonatomic = false;
#endif
WindowFunctionSupport support(context, fcinfo);
/*
* In window function case, we cannot see the argument datum
* in fcinfo. Instead, get them by WinGetFuncArgCurrent().
*/
if (support.IsWindowCall())
{
WindowObject winobj = support.GetWindowObject();
for (int i = 0; i < nargs; i++)
{
bool isnull;
Datum arg = WinGetFuncArgCurrent(winobj, i, &isnull);
args[i] = ToValue(arg, isnull, &argtypes[i]);
}
}
else
{
for (int i = 0; i < nargs; i++) {
#if PG_VERSION_NUM < 120000
args[i] = ToValue(fcinfo->arg[i], fcinfo->argnull[i], &argtypes[i]);
#else
args[i] = ToValue(fcinfo->args[i].value, fcinfo->args[i].isnull, &argtypes[i]);
#endif
}
}
Local<Object> recv = Local<Object>::New(xenv->isolate, xenv->recv);
Local<Function> fn =
Local<Function>::Cast(recv->GetInternalField(0));
Local<v8::Value> result =
DoCall(context, fn, recv, nargs, args, nonatomic);
if (rettype)
return ToDatum(result, &fcinfo->isnull, rettype);
else
PG_RETURN_VOID();
}
static Tuplestorestate *
CreateTupleStore(PG_FUNCTION_ARGS, TupleDesc *tupdesc)
{
Tuplestorestate *tupstore;
PG_TRY();
{
ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
MemoryContext per_query_ctx;
MemoryContext oldcontext;
plv8_proc *proc = (plv8_proc *) fcinfo->flinfo->fn_extra;
/* check to see if caller supports us returning a tuplestore */
if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("set-valued function called in context that cannot accept a set")));
if (!(rsinfo->allowedModes & SFRM_Materialize))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("materialize mode required, but it is not " \
"allowed in this context")));
if (!proc->functypclass)
proc->functypclass = get_call_result_type(fcinfo, NULL, NULL);
per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
oldcontext = MemoryContextSwitchTo(per_query_ctx);
tupstore = tuplestore_begin_heap(true, false, work_mem);
rsinfo->returnMode = SFRM_Materialize;
rsinfo->setResult = tupstore;
/* Build a tuple descriptor for our result type */
if (proc->rettype.typid == RECORDOID)
{
if (proc->functypclass != TYPEFUNC_COMPOSITE)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("function returning record called in context "
"that cannot accept type record")));
}
if (!rsinfo->setDesc)
{
*tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
rsinfo->setDesc = *tupdesc;
}
else
*tupdesc = rsinfo->setDesc;
MemoryContextSwitchTo(oldcontext);
}
PG_CATCH();
{
throw pg_error();
}
PG_END_TRY();
return tupstore;
}
static Datum
CallSRFunction(PG_FUNCTION_ARGS, plv8_exec_env *xenv,
int nargs, plv8_type argtypes[], plv8_type *rettype)
{
plv8_proc *proc = (plv8_proc *) fcinfo->flinfo->fn_extra;
TupleDesc tupdesc;
Tuplestorestate *tupstore;
#if PG_VERSION_NUM >= 110000
bool nonatomic = fcinfo->context &&
IsA(fcinfo->context, CallContext) &&
!castNode(CallContext, fcinfo->context)->atomic;
#else
bool nonatomic = false;
#endif
tupstore = CreateTupleStore(fcinfo, &tupdesc);
Handle<Context> context = xenv->localContext();
Context::Scope context_scope(context);
Converter conv(tupdesc, proc->functypclass == TYPEFUNC_SCALAR);
Handle<v8::Value> args[FUNC_MAX_ARGS + 1];
/*
* In case this is nested via SPI, stash pre-registered converters
* for the previous SRF.
*/
SRFSupport support(context, &conv, tupstore);
for (int i = 0; i < nargs; i++) {
#if PG_VERSION_NUM < 120000
args[i] = ToValue(fcinfo->arg[i], fcinfo->argnull[i], &argtypes[i]);
#else
args[i] = ToValue(fcinfo->args[i].value, fcinfo->args[i].isnull, &argtypes[i]);
#endif
}
Local<Object> recv = Local<Object>::New(xenv->isolate, xenv->recv);
Local<Function> fn =
Local<Function>::Cast(recv->GetInternalField(0));
Handle<v8::Value> result = DoCall(context, fn, recv, nargs, args, nonatomic);
if (result->IsUndefined())
{
// no additional values
}
else if (result->IsArray())