-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathBackend.c
More file actions
2400 lines (2167 loc) · 69.1 KB
/
Backend.c
File metadata and controls
2400 lines (2167 loc) · 69.1 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
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
/*
* Copyright (c) 2004-2025 Tada AB and other contributors, as listed below.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the The BSD 3-Clause License
* which accompanies this distribution, and is available at
* http://opensource.org/licenses/BSD-3-Clause
*
* Contributors:
* Tada AB - Thomas Hallgren
* PostgreSQL Global Development Group
* Chapman Flack
*/
#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 <utils/timeout.h>
#include <catalog/catalog.h>
#include <catalog/pg_proc.h>
#include <catalog/pg_type.h>
#if PG_VERSION_NUM >= 120000
#if defined(HAVE_DLOPEN) || PG_VERSION_NUM >= 160000 && ! defined(WIN32)
#include <dlfcn.h>
#endif
#define pg_dlopen(f) dlopen((f), RTLD_NOW | RTLD_GLOBAL)
#define pg_dlsym(h,s) dlsym((h), (s))
#define pg_dlclose(h) dlclose((h))
#define pg_dlerror() dlerror()
#else
#include <dynloader.h>
#endif
#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 "org_postgresql_pljava_internal_Backend_EarlyNatives.h"
#include "pljava/DualState.h"
#include "pljava/Invocation.h"
#include "pljava/InstallHelper.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"
/**
* \addtogroup JNI
* @{
*/
/* 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
/* About PGDLLEXPORT. It didn't exist before PG 9.0. In that revision it was
* defined (for Windows) as __declspec(dllexport) for MSVC, but as
* __declspec(dllimport) for any other toolchain. That was quickly changed
* (for 9.0.2 and ever since) as still __declspec(dllexport) for MSVC, but
* empty for any other toolchain. The explanation for that (in PG commit
* 844ed5d in November 2010) was that "dllexport and dllwrap don't work well
* together." There are records as far back as 2002 anyway
* (e.g. http://lists.gnu.org/archive/html/libtool/2002-09/msg00069.html)
* calling dllwrap deprecated, PL/Java's Maven build certainly doesn't
* use it, and I don't know what it would do if it did. It seems too brittle
* to rely on whatever PGDLLEXPORT might happen to mean across PG versions,
* and wiser for the moment to cleanly define something here, for the all of
* three(*) symbols that need it.
*
* The only case where it expands to anything is when building with Microsoft
* Visual Studio. When building with other toolchains it just goes away, even
* on Windows when building with MinGW (the only other Windows toolchain
* tested). MinGW can work either way: selectively exporting things based on
* a __declspec, or with the --export-all-symbols linker option so everything
* is visible, as on a *n*x platform. PL/Java could in theory choose either
* approach, but for one detail: there is a (*)fourth symbol that needs to be
* exported. PG_MODULE_MAGIC defines one, and being a PostgreSQL-supplied macro,
* it uses PGDLLEXPORT, which expands to nothing for MinGW (in recent PG
* versions anyway), forcing --export-all-symbols as the answer for MinGW.
*/
#ifdef _MSC_VER
#define PLJAVADLLEXPORT __declspec (dllexport)
#else
#define PLJAVADLLEXPORT
#endif
extern PLJAVADLLEXPORT void _PG_init(void);
#define LOCAL_REFERENCE_COUNT 128
MemoryContext JavaMemoryContext;
static JavaVM* s_javaVM = 0;
static jclass s_Backend_class;
static bool s_startingVM;
/*
* GUC states
*/
static char* libjvmlocation;
static char* vmoptions;
static char* modulepath;
static char* implementors;
static char* policy_urls;
static char* allow_unenforced;
static int statementCacheSize;
static bool allow_unenforced_udt;
static bool pljavaDebug;
static bool pljavaReleaseLingeringSavepoints;
static bool pljavaEnabled;
static int java_thread_pg_entry;
static int s_javaLogLevel;
#if PG_VERSION_NUM < 100000
bool integerDateTimes = false;
static void checkIntTimeType(void);
#endif
static char s_path_var_sep;
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 SQLChunkIOOrder_initialize(void);
extern void SQLInputFromChunk_initialize(void);
extern void SQLOutputToChunk_initialize(void);
extern void SQLOutputToTuple_initialize(void);
/*
* These typedefs are not exposed in Java's jni.h. Apparently you are supposed
* to be really determined if you want to use them. These are copy/pasted from
* src/hotspot/share/runtime/arguments.hpp. One silver lining is that they can
* be spelled here without the * used in the original, enabling them to be used
* succinctly to declare matching prototypes.
*/
typedef void JNICALL abort_hook_t(void);
typedef void JNICALL exit_hook_t(jint code);
typedef jint JNICALL vfprintf_hook_t(FILE *fp, const char *fmt, va_list args)
pg_attribute_printf(2, 0);
/*
* This private type is used here as a dynamically-sized list of JavaVMOption,
* which will later be copied to a struct of type JavaVMInitArgs (a type that
* jni.h does expose).
*/
typedef struct {
JavaVMOption* options;
unsigned int size;
unsigned int capacity;
} JVMOptList;
static void registerGUCOptions(void);
static jint initializeJavaVM(JVMOptList*);
static void JVMOptList_init(JVMOptList*);
static void JVMOptList_delete(JVMOptList*);
static void JVMOptList_add(JVMOptList*, const char*, void*, bool);
static void JVMOptList_addVisualVMName(JVMOptList*);
static void JVMOptList_addModuleMain(JVMOptList*);
static void addUserJVMOptions(JVMOptList*);
static char* getModulePath(const char*);
static abort_hook_t my_abort;
static exit_hook_t my_exit;
static vfprintf_hook_t my_vfprintf;
static void _destroyJavaVM(int, Datum);
static void initPLJavaClasses(void);
static void initJavaSession(void);
static void reLogWithChangedLevel(int);
#ifndef WIN32
#define USE_PLJAVA_SIGHANDLERS
#endif
#ifdef USE_PLJAVA_SIGHANDLERS
static void pljavaStatementCancelHandler(int);
static void pljavaDieHandler(int);
static void pljavaQuickDieHandler(int);
#endif
enum initstage
{
IS_FORMLESS_VOID,
IS_GUCS_REGISTERED,
IS_CAND_JVMLOCATION,
IS_CAND_POLICYURLS,
IS_PLJAVA_ENABLED,
IS_CAND_JVMOPENED,
IS_CREATEVM_SYM_FOUND,
IS_MISC_ONCE_DONE,
IS_JAVAVM_OPTLIST,
IS_JAVAVM_STARTED,
IS_SIGHANDLERS,
IS_PLJAVA_FOUND,
IS_PLJAVA_INSTALLING,
IS_COMPLETE
};
static enum initstage initstage = IS_FORMLESS_VOID;
static void *libjvm_handle;
static bool jvmStartedAtLeastOnce = false;
static bool alteredSettingsWereNeeded = false;
static bool loadAsExtensionFailed = false;
static bool seenVisualVMName;
static bool seenModuleMain;
static char const visualVMprefix[] = "-Dvisualvm.display.name=";
static char const moduleMainPrefix[] = "-Djdk.module.main=";
static char const policyUrlsGUC[] = "pljava.policy_urls";
static char const unenforcedGUC[] = "pljava.allow_unenforced";
/*
* In a background worker, _PG_init may be called very early, before much of
* the state needed during PL/Java initialization has even been set up. When
* that case is detected, initsequencer needs to go just as far as
* IS_GUCS_REGISTERED and then bail. The GUC assign hooks may then also be
* invoked as GUC values get copied from the lead process; they also need to
* return quickly (accomplished by checking this flag in ASSIGNRETURNIFNXACT).
* Further initialization is thus deferred until the first actual call arrives
* at the call handler, which resets this flag and rejoins the initsequencer.
* The same lazy approach needs to be followed during a pg_upgrade (which test-
* loads libraries, thus calling _PG_init). This flag is set for either case.
*/
static bool deferInit = false;
/*
* Whether Backend_warnJEP411() should emit a warning when called.
* Initially true, because it may be called very early from the deferInit check,
* if pg_upgrade is happening, and should always warn in that case. Thereafter
* false, unless set true in the initsequencer because InstallHelper_groundwork
* will be called (PL/Java being installed or upgraded), or in the validator
* handler because a PL/Java function has been declared or redeclared.
*/
static bool warnJEP411 = true;
/*
* Becomes true upon initialization of the Backend class if the Java property
* setting java.security.manager=disallow was explicitly in pljava.vmoptions.
* That is how to request the fallback nothing-is-enforced mode of operation
* that is the only mode available on Java >= 24. Only when all Java code is
* 100% trusted should PL/Java be run in this mode.
*/
static bool withoutEnforcement = false;
/*
* Don't bother with the warning unless the JVM in use is later than Java 11.
* 11 is the LTS release prior to the one where JEP 411 gets interesting (17).
* If a site is sticking to LTS releases, there will be plenty of time to warn
* on 17. If a site moves with non-LTS releases, start warning as soon as
* anything > 11 is used.
*
* Initially true, so there will be a warning unconditionally in a case
* (pg_upgrade) where a JVM hasn't been launched to learn its version).
*/
static bool javaGT11 = true;
static bool javaGE17 = false;
static void initsequencer(enum initstage is, bool tolerant);
static bool check_libjvm_location(
char **newval, void **extra, GucSource source);
static bool check_vmoptions(
char **newval, void **extra, GucSource source);
static bool check_modulepath(
char **newval, void **extra, GucSource source);
static bool check_policy_urls(
char **newval, void **extra, GucSource source);
static bool check_enabled(
bool *newval, void **extra, GucSource source);
static bool check_allow_unenforced_udt(
bool *newval, void **extra, GucSource source);
static bool check_java_thread_pg_entry(
int *newval, void **extra, GucSource source);
/* Check hooks will always allow "setting" a value that is the same as
* current; otherwise, it would be frustrating to have just found settings
* that work, and be unable to save them with ALTER DATABASE SET ... because
* the check hook is called for that too, and would say it is too late....
*/
static bool check_libjvm_location(
char **newval, void **extra, GucSource source)
{
if ( initstage < IS_CAND_JVMOPENED )
return true;
if ( libjvmlocation == *newval )
return true;
if ( libjvmlocation && *newval && 0 == strcmp(libjvmlocation, *newval) )
return true;
GUC_check_errmsg(
"too late to change \"pljava.libjvm_location\" setting");
GUC_check_errdetail(
"Changing the setting can have no effect after "
"PL/Java has found and opened the library it points to.");
GUC_check_errhint(
"To try a different value, exit this session and start a new one.");
return false;
}
static bool check_vmoptions(
char **newval, void **extra, GucSource source)
{
if ( initstage < IS_JAVAVM_OPTLIST )
return true;
if ( vmoptions == *newval )
return true;
if ( vmoptions && *newval && 0 == strcmp(vmoptions, *newval) )
return true;
GUC_check_errmsg(
"too late to change \"pljava.vmoptions\" setting");
GUC_check_errdetail(
"Changing the setting can have no effect after "
"PL/Java has started the Java virtual machine.");
GUC_check_errhint(
"To try a different value, exit this session and start a new one.");
return false;
}
static bool check_modulepath(
char **newval, void **extra, GucSource source)
{
if ( initstage < IS_JAVAVM_OPTLIST )
return true;
if ( modulepath == *newval )
return true;
if ( modulepath && *newval && 0 == strcmp(modulepath, *newval) )
return true;
GUC_check_errmsg(
"too late to change \"pljava.module_path\" setting");
GUC_check_errdetail(
"Changing the setting has no effect after "
"PL/Java has started the Java virtual machine.");
GUC_check_errhint(
"To try a different value, exit this session and start a new one.");
return false;
}
static bool check_policy_urls(
char **newval, void **extra, GucSource source)
{
if ( initstage < IS_JAVAVM_OPTLIST )
return true;
if ( policy_urls == *newval )
return true;
if ( policy_urls && *newval && 0 == strcmp(policy_urls, *newval) )
return true;
GUC_check_errmsg(
"too late to change \"pljava.policy_urls\" setting");
GUC_check_errdetail(
"Changing the setting has no effect after "
"PL/Java has started the Java virtual machine.");
GUC_check_errhint(
"To try a different value, exit this session and start a new one.");
return false;
}
static bool check_enabled(
bool *newval, void **extra, GucSource source)
{
if ( initstage < IS_PLJAVA_ENABLED )
return true;
if ( *newval )
return true;
GUC_check_errmsg(
"too late to change \"pljava.enable\" setting");
GUC_check_errdetail(
"Start-up has progressed past the point where it is checked.");
GUC_check_errhint(
"For another chance, exit this session and start a new one.");
return false;
}
static bool check_allow_unenforced_udt(
bool *newval, void **extra, GucSource source)
{
if ( initstage < IS_PLJAVA_FOUND )
return true;
if ( *newval || ! allow_unenforced_udt )
return true;
GUC_check_errmsg(
"too late to change \"pljava.allow_unenforced_udt\" setting");
GUC_check_errdetail(
"Once set, it cannot be reset in the same session.");
GUC_check_errhint(
"For another chance, exit this session and start a new one.");
return false;
}
static bool check_java_thread_pg_entry(
int *newval, void **extra, GucSource source)
{
if ( initstage < IS_PLJAVA_FOUND )
return true;
if ( java_thread_pg_entry == *newval )
return true;
GUC_check_errmsg(
"too late to change \"pljava.java_thread_pg_entry\" setting");
GUC_check_errdetail(
"Start-up has progressed past the point where it is checked.");
GUC_check_errhint(
"For another chance, exit this session and start a new one.");
return false;
}
#define ASSIGNHOOK(name,type) \
static void \
CppConcat(assign_,name)(type newval, void *extra); \
static void \
CppConcat(assign_,name)(type newval, void *extra)
#define ASSIGNRETURN(thing)
#define ASSIGNRETURNIFCHECK(thing)
#define ASSIGNRETURNIFNXACT(thing) \
if (! deferInit && pljavaViableXact()) ; else return
#define ASSIGNSTRINGHOOK(name) ASSIGNHOOK(name, const char *)
#define ASSIGNENUMHOOK(name) ASSIGNHOOK(name,int)
#define ENUMBOOTVAL(entry) ((entry).val)
#define ENUMHOOKRET true
static const struct config_enum_entry java_thread_pg_entry_options[] = {
{"allow", 0, false}, /* numeric value is bit-coded: */
{"error", 1, false}, /* 1: C code should refuse JNI calls on wrong thread */
/* 2: C code shouldn't call MonitorEnter/MonitorExit */
{"block", 3, false}, /* (3: check thread AND skip MonitorEnter/Exit) */
/* 4: *Java* code should refuse wrong-thread calls */
{"throw", 6, false}, /* (6: check in Java AND skip C MonitorEnter/Exit) */
{NULL, 0, false}
};
ASSIGNSTRINGHOOK(libjvm_location)
{
ASSIGNRETURNIFCHECK(newval);
libjvmlocation = (char *)newval;
if ( IS_FORMLESS_VOID < initstage && initstage < IS_CAND_JVMOPENED )
{
ASSIGNRETURNIFNXACT(newval);
alteredSettingsWereNeeded = true;
initsequencer( initstage, true);
}
ASSIGNRETURN(newval);
}
ASSIGNSTRINGHOOK(vmoptions)
{
ASSIGNRETURNIFCHECK(newval);
vmoptions = (char *)newval;
if ( IS_FORMLESS_VOID < initstage && initstage < IS_JAVAVM_OPTLIST )
{
ASSIGNRETURNIFNXACT(newval);
alteredSettingsWereNeeded = true;
initsequencer( initstage, true);
}
ASSIGNRETURN(newval);
}
ASSIGNSTRINGHOOK(modulepath)
{
ASSIGNRETURNIFCHECK(newval);
modulepath = (char *)newval;
if ( IS_FORMLESS_VOID < initstage && initstage < IS_JAVAVM_OPTLIST )
{
ASSIGNRETURNIFNXACT(newval);
alteredSettingsWereNeeded = true;
initsequencer( initstage, true);
}
ASSIGNRETURN(newval);
}
ASSIGNSTRINGHOOK(policy_urls)
{
ASSIGNRETURNIFCHECK(newval);
policy_urls = (char *)newval;
if ( IS_FORMLESS_VOID < initstage && initstage < IS_JAVAVM_OPTLIST )
{
alteredSettingsWereNeeded = true;
ASSIGNRETURNIFNXACT(newval);
initsequencer( initstage, true);
}
ASSIGNRETURN(newval);
}
ASSIGNSTRINGHOOK(allow_unenforced)
{
ASSIGNRETURNIFCHECK(newval);
allow_unenforced = (char *)newval;
if ( IS_PLJAVA_FOUND < initstage )
Function_clearFunctionCache();
ASSIGNRETURN(newval);
}
ASSIGNHOOK(enabled, bool)
{
ASSIGNRETURNIFCHECK(true);
pljavaEnabled = newval;
if ( IS_FORMLESS_VOID < initstage && initstage < IS_PLJAVA_ENABLED )
{
ASSIGNRETURNIFNXACT(true);
alteredSettingsWereNeeded = true;
initsequencer( initstage, true);
}
ASSIGNRETURN(true);
}
ASSIGNENUMHOOK(java_thread_pg_entry)
{
int val = newval;
ASSIGNRETURNIFCHECK(ENUMHOOKRET);
pljava_JNI_setThreadPolicy( !!(val&1) /*error*/, !(val&2) /*monitorops*/);
ASSIGNRETURN(ENUMHOOKRET);
}
/*
* There are a few ways to arrive in the initsequencer.
* 1. From _PG_init (called exactly once when the library is loaded for ANY
* reason).
* 1a. Because of the command LOAD 'libraryname';
* This case can be distinguished because _PG_init will have found the
* LOAD command and saved the 'libraryname' in pljavaLoadPath.
* 1b. Because of a CREATE FUNCTION naming this library. pljavaLoadPath will
* be NULL.
* 1c. By the first actual use of a PL/Java function, causing this library
* to be loaded. pljavaLoadPath will be NULL. The called function's Oid
* will be available to the call handler once we return from _PG_init,
* but it isn't (easily) available here.
* 2. From the call handler, if initialization isn't complete yet. That can only
* mean something failed in the earlier call to _PG_init, and whatever it was
* is highly likely to fail again. That may lead to the untidyness of
* duplicated diagnostic messages, but for now I like the belt-and-suspenders
* approach of making sure the init sequence gets as many chances as possible
* to succeed.
* 3. From a GUC assign hook, if the user has updated a setting that might allow
* initialization to succeed. It resumes from where it left off.
* 4. From the validator handler, if initialization isn't complete yet. That
* will definitely happen during pg_upgrade, which is a case where deferInit
* will have been set. The validator will then clear deferInit and try to get
* further in the init sequence. Importantly, pg_upgrade also sets
* check_function_bodies false, which limits the validator's work to a syntax
* check of the AS string. The validator therefore will not need to obtain a
* schemaLoader or do anything else that requires the sqlj schema to be fully
* populated (as, during pg_upgrade, it may not yet be). However, the
* validator handler must avoid any action that sets pljavaLoadPath, as a
* non-NULL value there would be treated below as case 1a, and trigger an
* attempt to set up the sqlj schema.
*
* In all cases, the sequence must progress as far as starting the VM and
* initializing the PL/Java classes. In all cases except 1a, that's enough,
* assuming the language handlers and schema have all been set up already (or,
* in case 1b, the user is intent on setting them up explicitly).
*
* In case 1a, we can go ahead and test for, and create, the schema, functions,
* and language entries as needed, using pljavaLoadPath as the library path
* if creating the language handler functions. One-stop shopping. (The presence
* of pljavaLoadPath in any of the other cases, such as resumption by an assign
* hook, indicates it is really a continuation of case 1a.)
*/
static void initsequencer(enum initstage is, bool tolerant)
{
JVMOptList optList;
Invocation ctx;
jint JNIresult;
char *greeting;
switch (is)
{
case IS_FORMLESS_VOID:
registerGUCOptions();
initstage = IS_GUCS_REGISTERED;
if ( deferInit )
return;
warnJEP411 = false;
/*FALLTHROUGH*/
case IS_GUCS_REGISTERED:
if ( NULL == libjvmlocation )
{
ereport(WARNING, (
errmsg("Java virtual machine not yet loaded"),
errdetail("location of libjvm is not configured"),
errhint("SET pljava.libjvm_location TO the correct "
"path to the jvm library (libjvm.so or jvm.dll, etc.)")));
goto check_tolerant;
}
initstage = IS_CAND_JVMLOCATION;
/*FALLTHROUGH*/
case IS_CAND_JVMLOCATION:
if ( NULL == policy_urls )
{
ereport(WARNING, (
errmsg("Java virtual machine not yet loaded"),
errdetail("Java policy URL(s) not configured"),
errhint("SET pljava.policy_urls TO the security policy "
"files PL/Java is to use.")));
goto check_tolerant;
}
initstage = IS_CAND_POLICYURLS;
/*FALLTHROUGH*/
case IS_CAND_POLICYURLS:
if ( ! pljavaEnabled )
{
ereport(WARNING, (
errmsg("Java virtual machine not yet loaded"),
errdetail(
"Pausing because \"pljava.enable\" is set \"off\". "),
errhint(
"After changing any other settings as necessary, set it "
"\"on\" to proceed.")));
goto check_tolerant;
}
initstage = IS_PLJAVA_ENABLED;
/*FALLTHROUGH*/
case IS_PLJAVA_ENABLED:
libjvm_handle = pg_dlopen(libjvmlocation);
if ( NULL == libjvm_handle )
{
ereport(WARNING, (
errmsg("Java virtual machine not yet loaded"),
errdetail("%s", (char *)pg_dlerror()),
errhint("SET pljava.libjvm_location TO the correct "
"path to the jvm library (libjvm.so or jvm.dll, etc.)")));
goto check_tolerant;
}
initstage = IS_CAND_JVMOPENED;
/*FALLTHROUGH*/
case IS_CAND_JVMOPENED:
pljava_createvm =
(jint (JNICALL *)(JavaVM **, void **, void *))
pg_dlsym(libjvm_handle, "JNI_CreateJavaVM");
if ( NULL == pljava_createvm )
{
/*
* If it hasn't got the symbol, it can't be the right
* library, so close/unload it so another can be tried.
* Format the dlerror string first: dlclose may clobber it.
*/
char *dle = MemoryContextStrdup(ErrorContext, pg_dlerror());
pg_dlclose(libjvm_handle);
initstage = IS_CAND_JVMLOCATION;
ereport(WARNING, (
errmsg("Java virtual machine not yet started"),
errdetail("%s", dle),
errhint("Is the file named in \"pljava.libjvm_location\" "
"the right one?")));
goto check_tolerant;
}
initstage = IS_CREATEVM_SYM_FOUND;
/*FALLTHROUGH*/
case IS_CREATEVM_SYM_FOUND:
s_javaLogLevel = INFO;
#if PG_VERSION_NUM < 100000
checkIntTimeType();
#endif
HashMap_initialize(); /* creates things in TopMemoryContext */
#ifdef PLJAVA_DEBUG
/* Hard setting for debug. Don't forget to recompile...
*/
pljavaDebug = 1;
#endif
initstage = IS_MISC_ONCE_DONE;
/*FALLTHROUGH*/
case IS_MISC_ONCE_DONE:
JVMOptList_init(&optList); /* uses CurrentMemoryContext */
seenVisualVMName = false;
seenModuleMain = false;
addUserJVMOptions(&optList);
if ( ! seenVisualVMName )
JVMOptList_addVisualVMName(&optList);
if ( ! seenModuleMain )
JVMOptList_addModuleMain(&optList);
JVMOptList_add(&optList, "abort", (void*)my_abort, true);
JVMOptList_add(&optList, "exit", (void*)my_exit, true);
JVMOptList_add(&optList, "vfprintf", (void*)my_vfprintf, true);
#ifndef GCJ
JVMOptList_add(&optList, "-Xrs", 0, true);
#endif
effectiveModulePath = getModulePath("--module-path=");
if(effectiveModulePath != 0)
{
JVMOptList_add(&optList, effectiveModulePath, 0, true);
}
initstage = IS_JAVAVM_OPTLIST;
/*FALLTHROUGH*/
case IS_JAVAVM_OPTLIST:
/* Register an on_proc_exit handler that destroys the VM if it has
* been started. It will also log a last-ditch message if the VM happens
* to rudely call exit() rather than returning a non-OK result.
*/
on_proc_exit(_destroyJavaVM, 0);
s_startingVM = true;
JNIresult = initializeJavaVM(&optList); /* frees the optList */
s_startingVM = false;
if( JNI_OK != JNIresult )
{
initstage = IS_MISC_ONCE_DONE; /* optList has been freed */
StaticAssertStmt(sizeof(jint) <= sizeof(long int),
"jint wider than long int?!");
ereport(WARNING,
(errmsg("failed to create Java virtual machine"),
errdetail("JNI_CreateJavaVM returned an error code: %ld",
(long int)JNIresult),
jvmStartedAtLeastOnce ?
errhint("Because an earlier attempt during this session "
"did start a VM before failing, this probably means your "
"Java runtime environment does not support more than one "
"VM creation per session. You may need to exit this "
"session and start a new one.") : 0));
goto check_tolerant;
}
jvmStartedAtLeastOnce = true;
elog(DEBUG2, "successfully created Java virtual machine");
initstage = IS_JAVAVM_STARTED;
/*FALLTHROUGH*/
case IS_JAVAVM_STARTED:
#ifdef USE_PLJAVA_SIGHANDLERS
pqsignal(SIGINT, pljavaStatementCancelHandler);
pqsignal(SIGTERM, pljavaDieHandler);
pqsignal(SIGQUIT, pljavaQuickDieHandler);
#endif
initstage = IS_SIGHANDLERS;
/*FALLTHROUGH*/
case IS_SIGHANDLERS:
Invocation_pushBootContext(&ctx);
PG_TRY();
{
initPLJavaClasses();
initJavaSession();
Invocation_popBootContext();
initstage = IS_PLJAVA_FOUND;
}
PG_CATCH();
{
MemoryContextSwitchTo(ctx.upperContext); /* leave ErrorContext */
Invocation_popBootContext();
initstage = IS_MISC_ONCE_DONE;
/* We can't stay here...
*/
if ( tolerant )
reLogWithChangedLevel(WARNING); /* so xact is not aborted */
else
{
EmitErrorReport(); /* no more unwinding, just log it */
/* Seeing an ERROR emitted to the log, without leaving the
* transaction aborted, would violate the principle of least
* astonishment. But at check_tolerant below, another ERROR will
* be thrown immediately, so the transaction effect will be as
* expected and this ERROR will contribute information beyond
* what is in the generic one thrown down there.
*/
FlushErrorState();
}
}
PG_END_TRY();
if ( IS_PLJAVA_FOUND != initstage )
{
/* JVM initialization failed for some reason. Destroy
* the VM if it exists. Perhaps the user will try
* fixing the pljava.module_path and make a new attempt.
*/
ereport(WARNING, (
errmsg("failed to load initial PL/Java classes"),
errhint("The most common reason is that \"pljava.module_path\" "
"needs to be set, naming the proper \"pljava.jar\" "
"and \"pljava-api.jar\" files, separated by the correct "
"path separator for this platform.")
));
pljava_DualState_unregister();
_destroyJavaVM(0, 0);
goto check_tolerant;
}
/*FALLTHROUGH*/
case IS_PLJAVA_FOUND:
greeting = InstallHelper_hello(); /*adjusts, freezes system properties*/
ereport(NULL != pljavaLoadPath ? NOTICE : DEBUG1, (
errmsg("PL/Java loaded"),
errdetail("versions:\n%s", greeting)));
pfree(greeting);
initstage = IS_PLJAVA_INSTALLING;
/*FALLTHROUGH*/
case IS_PLJAVA_INSTALLING:
if ( NULL != pljavaLoadPath )
{
warnJEP411 = javaGT11;
InstallHelper_groundwork(); /* sqlj schema, language handlers, ...*/
}
initstage = IS_COMPLETE;
/*FALLTHROUGH*/
case IS_COMPLETE:
pljavaLoadingAsExtension = false;
if ( alteredSettingsWereNeeded )
{
/* Use this StringInfoData to conditionally construct part of the
* hint string suggesting ALTER DATABASE ... SET ... FROM CURRENT
* provided the server is >= 9.2 where that will actually work.
* In 9.3, psprintf appeared, which would make this all simpler,
* but if 9.3+ were all that had to be supported, this would all
* be moot anyway. Doing the initStringInfo inside the ereport
* ensures the string is allocated in ErrorContext and won't leak.
* Don't remove the extra parens grouping
* (initStringInfo, appendStringInfo, errhint) ... with the parens,
* that's a comma expression, which is sequenced; without them, they
* are just function parameters with evaluation order unknown.
*/
StringInfoData buf;
ereport(NOTICE, (
errmsg("PL/Java successfully started after adjusting settings"),
(initStringInfo(&buf),
appendStringInfo(&buf, \
"using ALTER DATABASE %s SET ... FROM CURRENT or ", \
pljavaDbName()),
errhint("The settings that worked should be saved (%s"
"in the \"%s\" file). For a reminder of what has been set, "
"try: SELECT name, setting FROM pg_settings WHERE name LIKE"
" 'pljava.%%' AND source = 'session'",
buf.data,
superuser()
? PG_GETCONFIGOPTION("config_file")
: "postgresql.conf"))));
if ( loadAsExtensionFailed )
{
#if PG_VERSION_NUM < 130000
#define MOREHINT \
"\"CREATE EXTENSION pljava FROM unpackaged\""
#else
#define MOREHINT \
"\"CREATE EXTENSION pljava VERSION unpackaged\", " \
"then (after starting another new session) " \
"\"ALTER EXTENSION pljava UPDATE\""
#endif
ereport(NOTICE, (errmsg(
"PL/Java load successful after failed CREATE EXTENSION"),
errdetail(
"PL/Java is now installed, but not as an extension."),
errhint(
"To correct that, either COMMIT or ROLLBACK, make sure "
"the working settings are saved, exit this session, and "
"in a new session, either: "
"1. if committed, run "
MOREHINT
", or 2. "
"if rolled back, simply \"CREATE EXTENSION pljava\" again."
)));
#undef MOREHINT
}
}
return;
default:
ereport(ERROR, (
errmsg("cannot set up PL/Java"),
errdetail(
"An unexpected stage was reached in the startup sequence."),
errhint(
"Please report the circumstances to the PL/Java maintainers.")
));
}
check_tolerant:
if ( pljavaLoadingAsExtension )
{
tolerant = false;
loadAsExtensionFailed = true;
pljavaLoadingAsExtension = false;
}
if ( !tolerant )
{
ereport(ERROR, (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg(
"cannot use PL/Java before successfully completing its setup"),
errhint(
"Check the log for messages closely preceding this one, "
"detailing what step of setup failed and what will be needed, "
"probably setting one of the \"pljava.\" configuration "
"variables, to complete the setup. If there is not enough "
"help in the log, try again with different settings for "
"\"log_min_messages\" or \"log_error_verbosity\".")));
}
}
/*
* A function having everything to do with logging, which ought to be factored
* out one day to make a start on the Thoughts-on-logging wiki ideas.
*/
static void reLogWithChangedLevel(int level)
{
ErrorData *edata = CopyErrorData();
int sqlstate = edata->sqlerrcode;
int category = ERRCODE_TO_CATEGORY(sqlstate);
FlushErrorState();
if ( WARNING > level )
{
if ( ERRCODE_SUCCESSFUL_COMPLETION != category )
sqlstate = ERRCODE_SUCCESSFUL_COMPLETION;
}
else if ( WARNING == level )
{
if ( ERRCODE_WARNING != category && ERRCODE_NO_DATA != category )
sqlstate = ERRCODE_WARNING;
}
else if ( ERRCODE_WARNING == category || ERRCODE_NO_DATA == category ||
ERRCODE_SUCCESSFUL_COMPLETION == category )
sqlstate = ERRCODE_INTERNAL_ERROR;
edata->elevel = level;
edata->sqlerrcode = sqlstate;
PG_TRY();
{
ThrowErrorData(edata);
}
PG_CATCH();
{
FreeErrorData(edata); /* otherwise this wouldn't happen in ERROR case */
PG_RE_THROW();
}
PG_END_TRY();
FreeErrorData(edata);
}
void _PG_init()
{
char *sep;
if ( IS_PLJAVA_INSTALLING == initstage )
return; /* creating handler functions will cause recursive call */
InstallHelper_earlyHello();
/*
* Find the platform's path separator. Java knows it, but that's no help in
* preparing the launch options before it is launched. PostgreSQL knows what
* it is, but won't directly say; give it some choices and it'll pick one.
* Alternatively, let Maven or Ant determine and add a -D at build time from
* the path.separator property. Maybe that's cleaner?
*/
sep = first_path_var_separator(":;");
if ( NULL == sep )
elog(ERROR,
"PL/Java cannot determine the path separator this platform uses");
s_path_var_sep = *sep;
if ( InstallHelper_shouldDeferInit() )
deferInit = true;
else
pljavaCheckExtension( NULL);
initsequencer( initstage, true);
}
static void initPLJavaClasses(void)
{
jfieldID fID;
int javaMajor;
JNINativeMethod backendMethods[] =
{
{
"isCallingJava",
"()Z",
Java_org_postgresql_pljava_internal_Backend_isCallingJava
},
{
"isReleaseLingeringSavepoints",
"()Z",