forked from tada/pljava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBackend.c
More file actions
957 lines (853 loc) · 21.4 KB
/
Copy pathBackend.c
File metadata and controls
957 lines (853 loc) · 21.4 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
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
/*
* Copyright (c) 2004, 2005, 2006 TADA AB - Taby Sweden
* Copyright (c) 2009, 2010, 2011 PostgreSQL Global Development Group
*
* Distributed under the terms shown in the file COPYRIGHT
* found in the root folder of this project or at
* http://wiki.tada.se/index.php?title=PLJava_License
*
* @author Thomas Hallgren
*/
#include <postgres.h>
#include <miscadmin.h>
#ifndef WIN32
#include <libpq/pqsignal.h>
#endif
#include <executor/spi.h>
#include <commands/trigger.h>
#include <utils/elog.h>
#include <utils/guc.h>
#include <fmgr.h>
#include <access/heapam.h>
#include <utils/syscache.h>
#include <catalog/catalog.h>
#include <catalog/pg_proc.h>
#include <catalog/pg_type.h>
#include <storage/ipc.h>
#include <storage/proc.h>
#include <stdio.h>
#include <ctype.h>
#include <unistd.h>
#include "org_postgresql_pljava_internal_Backend.h"
#include "pljava/Invocation.h"
#include "pljava/Function.h"
#include "pljava/HashMap.h"
#include "pljava/Exception.h"
#include "pljava/Backend.h"
#include "pljava/Session.h"
#include "pljava/SPI.h"
#include "pljava/type/String.h"
/* Example format: "/usr/local/pgsql/lib" */
#ifndef PKGLIBDIR
#error "PKGLIBDIR needs to be defined to compile this file."
#endif
/* Include the 'magic block' that PostgreSQL 8.2 and up will use to ensure
* that a module is not loaded into an incompatible server.
*/
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
#ifdef PG_GETCONFIGOPTION
#error The macro PG_GETCONFIGOPTION needs to be renamed.
#endif
#if ( PGSQL_MAJOR_VER > 8 )
#if ( PGSQL_MINOR_VER > 0 )
#define PG_GETCONFIGOPTION(key) GetConfigOption(key, false, true)
#else
#define PG_GETCONFIGOPTION(key) GetConfigOption(key, true)
#endif
#else
#define PG_GETCONFIGOPTION(key) GetConfigOption(key)
#endif
#define LOCAL_REFERENCE_COUNT 128
jlong mainThreadId;
static JavaVM* s_javaVM = 0;
static jclass s_Backend_class;
static jmethodID s_setTrusted;
static char* vmoptions;
static char* classpath;
static int statementCacheSize;
static bool pljavaDebug;
static bool pljavaReleaseLingeringSavepoints;
static bool s_currentTrust;
static int s_javaLogLevel;
bool integerDateTimes = false;
extern void Invocation_initialize(void);
extern void Exception_initialize(void);
extern void Exception_initialize2(void);
extern void HashMap_initialize(void);
extern void SPI_initialize(void);
extern void Type_initialize(void);
extern void Function_initialize(void);
extern void Session_initialize(void);
extern void PgSavepoint_initialize(void);
extern void XactListener_initialize(void);
extern void SubXactListener_initialize(void);
extern void SQLInputFromChunk_initialize(void);
extern void SQLOutputToChunk_initialize(void);
extern void SQLInputFromTuple_initialize(void);
extern void SQLOutputToTuple_initialize(void);
static void initPLJavaClasses(void)
{
jfieldID tlField;
JNINativeMethod backendMethods[] =
{
{
"isCallingJava",
"()Z",
Java_org_postgresql_pljava_internal_Backend_isCallingJava
},
{
"isReleaseLingeringSavepoints",
"()Z",
Java_org_postgresql_pljava_internal_Backend_isReleaseLingeringSavepoints
},
{
"_getConfigOption",
"(Ljava/lang/String;)Ljava/lang/String;",
Java_org_postgresql_pljava_internal_Backend__1getConfigOption
},
{
"_getStatementCacheSize",
"()I",
Java_org_postgresql_pljava_internal_Backend__1getStatementCacheSize
},
{
"_log",
"(ILjava/lang/String;)V",
Java_org_postgresql_pljava_internal_Backend__1log
},
{
"_clearFunctionCache",
"()V",
Java_org_postgresql_pljava_internal_Backend__1clearFunctionCache
},
{ 0, 0, 0 }
};
Exception_initialize();
elog(DEBUG1, "Getting Backend class pljava.jar");
s_Backend_class = PgObject_getJavaClass("org/postgresql/pljava/internal/Backend");
elog(DEBUG1, "Backend class was there");
PgObject_registerNatives2(s_Backend_class, backendMethods);
tlField = PgObject_getStaticJavaField(s_Backend_class, "THREADLOCK", "Ljava/lang/Object;");
JNI_setThreadLock(JNI_getStaticObjectField(s_Backend_class, tlField));
Invocation_initialize();
Exception_initialize2();
SPI_initialize();
Type_initialize();
Function_initialize();
Session_initialize();
PgSavepoint_initialize();
XactListener_initialize();
SubXactListener_initialize();
SQLInputFromChunk_initialize();
SQLOutputToChunk_initialize();
SQLInputFromTuple_initialize();
SQLOutputToTuple_initialize();
s_setTrusted = PgObject_getStaticJavaMethod(s_Backend_class, "setTrusted", "(Z)V");
}
/**
* Initialize security
*/
void Backend_setJavaSecurity(bool trusted)
{
if(trusted != s_currentTrust)
{
/* GCJ has major issues here. Real work on SecurityManager and
* related classes has just started in version 4.0.0.
*/
#ifndef GCJ
JNI_callStaticVoidMethod(s_Backend_class, s_setTrusted, (jboolean)trusted);
if(JNI_exceptionCheck())
{
JNI_exceptionDescribe();
JNI_exceptionClear();
ereport(ERROR, (
errcode(ERRCODE_INTERNAL_ERROR),
errmsg("Unable to initialize java security")));
}
#endif
s_currentTrust = trusted;
}
}
int Backend_setJavaLogLevel(int logLevel)
{
int oldLevel = s_javaLogLevel;
s_javaLogLevel = logLevel;
return oldLevel;
}
/**
* Special purpose logging function called from JNI when verbose is enabled.
*/
static jint JNICALL my_vfprintf(FILE* fp, const char* format, va_list args)
{
char buf[1024];
char* ep;
char* bp = buf;
vsnprintf(buf, sizeof(buf), format, args);
/* Trim off trailing newline and other whitespace.
*/
ep = bp + strlen(bp) - 1;
while(ep >= bp && isspace(*ep))
--ep;
++ep;
*ep = 0;
elog(s_javaLogLevel, "%s", buf);
return 0;
}
/*
* Append those parts of path that has not yet been appended. The HashMap unique is
* keeping track of what has been appended already. First appended part will be
* prefixed with prefix.
*/
static void appendPathParts(const char* path, StringInfoData* bld, HashMap unique, const char* prefix)
{
StringInfoData buf;
if(path == 0 || strlen(path) == 0)
return;
for (;;)
{
char* pathPart;
size_t len;
if(*path == 0)
break;
len = strcspn(path, ";:");
if(len == 1 && *(path+1) == ':' && isalnum(*path))
/*
* Windows drive designator, leave it "as is".
*/
len = strcspn(path+2, ";:") + 2;
else
if(len == 0)
{
/* Ignore zero length components.
*/
++path;
continue;
}
initStringInfo(&buf);
if(*path == '$')
{
if(len == 7 || (strcspn(path, "/\\") == 7 && strncmp(path, "$libdir", 7) == 0))
{
len -= 7;
path += 7;
appendStringInfo(&buf, PKGLIBDIR);
}
else
ereport(ERROR, (
errcode(ERRCODE_INVALID_NAME),
errmsg("invalid macro name '%*s' in dynamic library path", (int)len, path)));
}
if(len > 0)
{
appendBinaryStringInfo(&buf, path, len);
path += len;
}
pathPart = buf.data;
if(HashMap_getByString(unique, pathPart) == 0)
{
if(HashMap_size(unique) == 0)
appendStringInfo(bld, "%s", prefix);
else
#if defined(WIN32)
appendStringInfoChar(bld, ';');
#else
appendStringInfoChar(bld, ':');
#endif
appendStringInfo(bld, "%s", pathPart);
HashMap_putByString(unique, pathPart, (void*)1);
}
pfree(pathPart);
if(*path == 0)
break;
++path; /* Skip ':' */
}
}
/*
* Get the CLASSPATH. Result is always freshly palloc'd.
*/
static char* getClassPath(const char* prefix)
{
char* path;
HashMap unique = HashMap_create(13, CurrentMemoryContext);
StringInfoData buf;
initStringInfo(&buf);
appendPathParts(classpath, &buf, unique, prefix);
appendPathParts(getenv("CLASSPATH"), &buf, unique, prefix);
PgObject_free((PgObject)unique);
path = buf.data;
if(strlen(path) == 0)
{
pfree(path);
path = 0;
}
return path;
}
#if !defined(WIN32)
static void pljavaStatementCancelHandler(int signum)
{
if(!proc_exit_inprogress)
{
/* Never service the interrupt immediately. In order to find out if
* its safe, we would need to know what kind of threading mechanism
* the VM uses. That would count for a lot of conditional code.
*/
QueryCancelPending = true;
InterruptPending = true;
}
}
static void pljavaDieHandler(int signum)
{
if(!proc_exit_inprogress)
{
/* Never service the interrupt immediately. In order to find out if
* its safe, we would need to know what kind of threading mechanism
* the VM uses. That would count for a lot of conditional code.
*/
ProcDiePending = true;
InterruptPending = true;
}
}
static void pljavaQuickDieHandler(int signum)
{
/* Just die. No ereporting here since we don't know what thread this is.
*/
exit(1);
}
static sigjmp_buf recoverBuf;
static void terminationTimeoutHandler(int signum)
{
kill(MyProcPid, SIGQUIT);
/* Some sleep to get the SIGQUIT a chance to generate
* the needed output.
*/
pg_usleep(1);
/* JavaVM did not die within the alloted time
*/
siglongjmp(recoverBuf, 1);
}
#endif
/*
* proc_exit callback to tear down the JVM
*/
static void _destroyJavaVM(int status, Datum dummy)
{
if(s_javaVM != 0)
{
Invocation ctx;
#if !defined(WIN32)
pqsigfunc saveSigAlrm;
Invocation_pushInvocation(&ctx, false);
if(sigsetjmp(recoverBuf, 1) != 0)
{
elog(DEBUG1, "JavaVM destroyed with force");
s_javaVM = 0;
return;
}
saveSigAlrm = pqsignal(SIGALRM, terminationTimeoutHandler);
enable_sig_alarm(5000, false);
elog(DEBUG1, "Destroying JavaVM...");
JNI_destroyVM(s_javaVM);
disable_sig_alarm(false);
pqsignal(SIGALRM, saveSigAlrm);
#else
Invocation_pushInvocation(&ctx, false);
elog(DEBUG1, "Destroying JavaVM...");
JNI_destroyVM(s_javaVM);
#endif
elog(DEBUG1, "JavaVM destroyed");
s_javaVM = 0;
currentInvocation = 0;
}
}
typedef struct {
JavaVMOption* options;
unsigned int size;
unsigned int capacity;
} JVMOptList;
static void JVMOptList_init(JVMOptList* jol)
{
jol->options = (JavaVMOption*)palloc(10 * sizeof(JavaVMOption));
jol->size = 0;
jol->capacity = 10;
}
static void JVMOptList_delete(JVMOptList* jol)
{
JavaVMOption* opt = jol->options;
JavaVMOption* top = opt + jol->size;
while(opt < top)
{
pfree(opt->optionString);
opt++;
}
pfree(jol->options);
}
static void JVMOptList_add(JVMOptList* jol, const char* optString, void* extraInfo, bool mustCopy)
{
JavaVMOption* added;
int newPos = jol->size;
if(newPos >= jol->capacity)
{
int newCap = jol->capacity * 2;
JavaVMOption* newOpts = (JavaVMOption*)palloc(newCap * sizeof(JavaVMOption));
memcpy(newOpts, jol->options, newPos * sizeof(JavaVMOption));
pfree(jol->options);
jol->options = newOpts;
jol->capacity = newCap;
}
added = jol->options + newPos;
if(mustCopy)
optString = pstrdup(optString);
added->optionString = (char*)optString;
added->extraInfo = extraInfo;
jol->size++;
elog(DEBUG1, "Added JVM option string \"%s\"", optString);
}
/* Split JVM options. The string is split on whitespace unless the
* whitespace is found within a string or is escaped by backslash. A
* backslash escaped quote is not considered a string delimiter.
*/
static void addUserJVMOptions(JVMOptList* optList)
{
const char* cp = vmoptions;
if(cp != NULL)
{
StringInfoData buf;
char quote = 0;
char c;
initStringInfo(&buf);
for(;;)
{
c = *cp++;
switch(c)
{
case 0:
break;
case '"':
case '\'':
if(quote == c)
quote = 0;
else
quote = c;
appendStringInfoChar(&buf, c);
continue;
case '\\':
appendStringInfoChar(&buf, '\\');
c = *cp++; /* Interpret next character verbatim */
if(c == 0)
break;
appendStringInfoChar(&buf, c);
continue;
default:
if(quote == 0 && isspace((int)c))
{
while((c = *cp++) != 0)
{
if(!isspace((int)c))
break;
}
if(c == 0)
break;
if(c != '-')
appendStringInfoChar(&buf, ' ');
else if(buf.len > 0)
{
/* Whitespace followed by '-' triggers new
* option declaration.
*/
JVMOptList_add(optList, buf.data, 0, true);
buf.len = 0;
buf.data[0] = 0;
}
}
appendStringInfoChar(&buf, c);
continue;
}
break;
}
if(buf.len > 0)
JVMOptList_add(optList, buf.data, 0, true);
pfree(buf.data);
}
}
/**
* Initialize the session
*/
static void initJavaSession(void)
{
jclass sessionClass = PgObject_getJavaClass("org/postgresql/pljava/internal/Session");
jmethodID init = PgObject_getStaticJavaMethod(sessionClass, "init", "()J");
mainThreadId = JNI_callStaticLongMethod(sessionClass, init);
JNI_deleteLocalRef(sessionClass);
if(JNI_exceptionCheck())
{
JNI_exceptionDescribe();
JNI_exceptionClear();
ereport(ERROR, (
errcode(ERRCODE_INTERNAL_ERROR),
errmsg("Unable to initialize java session")));
}
}
static void checkIntTimeType(void)
{
const char* idt = PG_GETCONFIGOPTION("integer_datetimes");
integerDateTimes = (strcmp(idt, "on") == 0);
elog(DEBUG1, integerDateTimes ? "Using integer_datetimes" : "Not using integer_datetimes");
}
static bool s_firstTimeInit = true;
static void initializeJavaVM(void)
{
jboolean jstat;
JavaVMInitArgs vm_args;
JVMOptList optList;
JVMOptList_init(&optList);
if(s_firstTimeInit)
{
s_firstTimeInit = false;
s_javaLogLevel = INFO;
checkIntTimeType();
HashMap_initialize();
DefineCustomStringVariable(
"pljava.vmoptions",
"Options sent to the JVM when it is created",
NULL,
&vmoptions,
#if (PGSQL_MAJOR_VER > 8 || (PGSQL_MAJOR_VER == 8 && PGSQL_MINOR_VER > 3))
NULL,
#endif
PGC_USERSET,
#if (PGSQL_MAJOR_VER > 8 || (PGSQL_MAJOR_VER == 8 && PGSQL_MINOR_VER > 3))
0,
#endif
#if (PGSQL_MAJOR_VER > 9 || (PGSQL_MAJOR_VER == 9 && PGSQL_MINOR_VER > 0))
NULL,
#endif
NULL, NULL);
DefineCustomStringVariable(
"pljava.classpath",
"Classpath used by the JVM",
NULL,
&classpath,
#if (PGSQL_MAJOR_VER > 8 || (PGSQL_MAJOR_VER == 8 && PGSQL_MINOR_VER > 3))
NULL,
#endif
PGC_USERSET,
#if (PGSQL_MAJOR_VER > 8 || (PGSQL_MAJOR_VER == 8 && PGSQL_MINOR_VER > 3))
0,
#endif
#if (PGSQL_MAJOR_VER > 9 || (PGSQL_MAJOR_VER == 9 && PGSQL_MINOR_VER > 0))
NULL,
#endif
NULL, NULL);
DefineCustomBoolVariable(
"pljava.debug",
"Stop the backend to attach a debugger",
NULL,
&pljavaDebug,
#if (PGSQL_MAJOR_VER > 8 || (PGSQL_MAJOR_VER == 8 && PGSQL_MINOR_VER > 3))
false,
#endif
PGC_USERSET,
#if (PGSQL_MAJOR_VER > 8 || (PGSQL_MAJOR_VER == 8 && PGSQL_MINOR_VER > 3))
0,
#endif
#if (PGSQL_MAJOR_VER > 9 || (PGSQL_MAJOR_VER == 9 && PGSQL_MINOR_VER > 0))
NULL,
#endif
NULL, NULL);
DefineCustomIntVariable(
"pljava.statement_cache_size",
"Size of the prepared statement MRU cache",
NULL,
&statementCacheSize,
#if (PGSQL_MAJOR_VER > 8 || (PGSQL_MAJOR_VER == 8 && PGSQL_MINOR_VER > 3))
11,
#endif
0, 512,
PGC_USERSET,
#if (PGSQL_MAJOR_VER > 8 || (PGSQL_MAJOR_VER == 8 && PGSQL_MINOR_VER > 3))
0,
#endif
#if (PGSQL_MAJOR_VER > 9 || (PGSQL_MAJOR_VER == 9 && PGSQL_MINOR_VER > 0))
NULL,
#endif
NULL, NULL);
DefineCustomBoolVariable(
"pljava.release_lingering_savepoints",
"If true, lingering savepoints will be released on function exit. If false, the will be rolled back",
NULL,
&pljavaReleaseLingeringSavepoints,
#if (PGSQL_MAJOR_VER > 8 || (PGSQL_MAJOR_VER == 8 && PGSQL_MINOR_VER > 3))
false,
#endif
PGC_USERSET,
#if (PGSQL_MAJOR_VER > 8 || (PGSQL_MAJOR_VER == 8 && PGSQL_MINOR_VER > 3))
0,
#endif
#if (PGSQL_MAJOR_VER > 9 || (PGSQL_MAJOR_VER == 9 && PGSQL_MINOR_VER > 0))
NULL,
#endif
NULL, NULL);
EmitWarningsOnPlaceholders("pljava");
s_firstTimeInit = false;
}
#ifdef PLJAVA_DEBUG
/* Hard setting for debug. Don't forget to recompile...
*/
pljavaDebug = 1;
#endif
addUserJVMOptions(&optList);
effectiveClassPath = getClassPath("-Djava.class.path=");
if(effectiveClassPath != 0)
{
JVMOptList_add(&optList, effectiveClassPath, 0, true);
}
/**
* As stipulated by JRT-2003
*/
JVMOptList_add(&optList,
"-Dsqlj.defaultconnection=jdbc:default:connection",
0, true);
JVMOptList_add(&optList, "vfprintf", (void*)my_vfprintf, true);
#ifndef GCJ
JVMOptList_add(&optList, "-Xrs", 0, true);
#endif
if(pljavaDebug)
{
elog(INFO, "Backend pid = %d. Attach the debugger and set pljavaDebug to false to continue", getpid());
while(pljavaDebug)
pg_usleep(1000000L);
}
vm_args.nOptions = optList.size;
vm_args.options = optList.options;
vm_args.version = JNI_VERSION_1_4;
vm_args.ignoreUnrecognized = JNI_FALSE;
elog(DEBUG1, "Creating JavaVM");
jstat = JNI_createVM(&s_javaVM, &vm_args);
if(jstat == JNI_OK && JNI_exceptionCheck())
{
JNI_exceptionDescribe();
JNI_exceptionClear();
jstat = JNI_ERR;
}
JVMOptList_delete(&optList);
if(jstat != JNI_OK)
ereport(ERROR, (errmsg("Failed to create Java VM")));
#if !defined(WIN32)
pqsignal(SIGINT, pljavaStatementCancelHandler);
pqsignal(SIGTERM, pljavaDieHandler);
pqsignal(SIGQUIT, pljavaQuickDieHandler);
#endif
elog(DEBUG1, "JavaVM created");
/* Register an on_proc_exit handler that destroys the VM
*/
on_proc_exit(_destroyJavaVM, 0);
initPLJavaClasses();
initJavaSession();
}
static Datum internalCallHandler(bool trusted, PG_FUNCTION_ARGS);
extern Datum javau_call_handler(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(javau_call_handler);
/*
* This is the entry point for all untrusted calls.
*/
Datum javau_call_handler(PG_FUNCTION_ARGS)
{
return internalCallHandler(false, fcinfo);
}
extern Datum java_call_handler(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(java_call_handler);
/*
* This is the entry point for all trusted calls.
*/
Datum java_call_handler(PG_FUNCTION_ARGS)
{
return internalCallHandler(true, fcinfo);
}
static Datum internalCallHandler(bool trusted, PG_FUNCTION_ARGS)
{
Invocation ctx;
Datum retval = 0;
if(s_javaVM == 0)
{
Invocation_pushBootContext(&ctx);
PG_TRY();
{
initializeJavaVM();
Invocation_popBootContext();
}
PG_CATCH();
{
Invocation_popBootContext();
/* JVM initialization failed for some reason. Destroy
* the VM if it exists. Perhaps the user will try
* fixing the pljava.classpath and make a new attempt.
*/
_destroyJavaVM(0, 0);
/* We can't stay here...
*/
PG_RE_THROW();
}
PG_END_TRY();
/* Force initial setting
*/
s_currentTrust = !trusted;
}
Invocation_pushInvocation(&ctx, trusted);
PG_TRY();
{
Function function = Function_getFunction(fcinfo);
if(CALLED_AS_TRIGGER(fcinfo))
{
/* Called as a trigger procedure
*/
retval = Function_invokeTrigger(function, fcinfo);
}
else
{
/* Called as a function
*/
retval = Function_invoke(function, fcinfo);
}
Invocation_popInvocation(false);
}
PG_CATCH();
{
Invocation_popInvocation(true);
PG_RE_THROW();
}
PG_END_TRY();
return retval;
}
/****************************************
* JNI methods
****************************************/
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
{
return JNI_VERSION_1_4;
}
/*
* Class: org_postgresql_pljava_internal_Backend
* Method: _getConfigOption
* Signature: (Ljava/lang/String;)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL
JNICALL Java_org_postgresql_pljava_internal_Backend__1getConfigOption(JNIEnv* env, jclass cls, jstring jkey)
{
jstring result = 0;
BEGIN_NATIVE
char* key = String_createNTS(jkey);
if(key != 0)
{
PG_TRY();
{
const char *value = PG_GETCONFIGOPTION(key);
pfree(key);
if(value != 0)
result = String_createJavaStringFromNTS(value);
}
PG_CATCH();
{
Exception_throw_ERROR("GetConfigOption");
}
PG_END_TRY();
}
END_NATIVE
return result;
}
/*
* Class: org_postgresql_pljava_internal_Backend
* Method: _getStatementCacheSize
* Signature: ()I
*/
JNIEXPORT jint JNICALL
Java_org_postgresql_pljava_internal_Backend__1getStatementCacheSize(JNIEnv* env, jclass cls)
{
return statementCacheSize;
}
/*
* Class: org_postgresql_pljava_internal_Backend
* Method: _log
* Signature: (ILjava/lang/String;)V
*/
JNIEXPORT void JNICALL
JNICALL Java_org_postgresql_pljava_internal_Backend__1log(JNIEnv* env, jclass cls, jint logLevel, jstring jstr)
{
BEGIN_NATIVE_NO_ERRCHECK
char* str = String_createNTS(jstr);
if(str != 0)
{
/* elog uses printf formatting but the logger does not so we must escape all
* '%' in the string.
*/
char c;
const char* cp;
int percentCount = 0;
for(cp = str; (c = *cp) != 0; ++cp)
{
if(c == '%')
++percentCount;
}
if(percentCount > 0)
{
/* Make room to expand all "%" to "%%"
*/
char* str2 = palloc((cp - str) + percentCount + 1);
char* cp2 = str2;
/* Expand... */
for(cp = str; (c = *cp) != 0; ++cp)
{
if(c == '%')
*cp2++ = c;
*cp2++ = c;
}
*cp2 = 0;
pfree(str);
str = str2;
}
PG_TRY();
{
elog(logLevel, "%s", str);
pfree(str);
}
PG_CATCH();
{
Exception_throw_ERROR("ereport");
}
PG_END_TRY();
}
END_NATIVE
}
/*
* Class: org_postgresql_pljava_internal_Backend
* Method: isCallingJava
* Signature: ()Z
*/
JNIEXPORT jboolean JNICALL
Java_org_postgresql_pljava_internal_Backend_isCallingJava(JNIEnv* env, jclass cls)
{
return JNI_isCallingJava();
}
/*
* Class: org_postgresql_pljava_internal_Backend
* Method: isReleaseLingeringSavepoints
* Signature: ()Z
*/
JNIEXPORT jboolean JNICALL
Java_org_postgresql_pljava_internal_Backend_isReleaseLingeringSavepoints(JNIEnv* env, jclass cls)
{
return pljavaReleaseLingeringSavepoints ? JNI_TRUE : JNI_FALSE;
}
/*
* Class: org_postgresql_pljava_internal_Backend
* Method: _clearFunctionCache
* Signature: ()V
*/
JNIEXPORT void JNICALL
Java_org_postgresql_pljava_internal_Backend__1clearFunctionCache(JNIEnv* env, jclass cls)
{
BEGIN_NATIVE_NO_ERRCHECK
Function_clearFunctionCache();
END_NATIVE
}