/
why.cpp
6788 lines (5514 loc) · 157 KB
/
why.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
994
995
996
997
998
999
1000
/*
* PROGRAM: JRD Access Method
* MODULE: why.cpp
* DESCRIPTION: Universal Y-valve
*
* The contents of this file are subject to the Interbase Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy
* of the License at http://www.Inprise.com/IPL.html
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
* or implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code was created by Inprise Corporation
* and its predecessors. Portions created by Inprise Corporation are
* Copyright (C) Inprise Corporation.
*
* All Rights Reserved.
* Contributor(s): ______________________________________.
*
* Dmitry Yemanov
* Sean Leyne
* Alex Peshkoff
* Adriano dos Santos Fernandes
*
*/
#include "firebird.h"
#define FB_UsedInYValve true
#include "firebird/Interface.h"
#include "memory_routines.h"
#include "iberror.h"
#include "../yvalve/YObjects.h"
#include "firebird/impl/sqlda_pub.h"
#include "../common/gdsassert.h"
#include "../common/db_alias.h"
#include "../common/StatementMetadata.h"
#include "../common/StatusHolder.h"
#include "../common/ThreadStart.h"
#include "../common/isc_proto.h"
#include "../common/isc_f_proto.h"
#include "../common/utils_proto.h"
#include "../common/IntlParametersBlock.h"
#include "../common/os/isc_i_proto.h"
#include "../common/os/path_utils.h"
#include "../common/classes/alloc.h"
#include "../common/classes/array.h"
#include "../common/classes/stack.h"
#include "../common/classes/fb_string.h"
#include "../common/classes/fb_atomic.h"
#include "../common/classes/init.h"
#include "../common/classes/rwlock.h"
#include "../common/classes/semaphore.h"
#include "../common/classes/ClumpletWriter.h"
#include "../common/classes/FpeControl.h"
#include "../common/classes/GenericMap.h"
#include "../common/classes/GetPlugins.h"
#include "../common/classes/fb_tls.h"
#include "../common/status.h"
#include "../common/classes/InternalMessageBuffer.h"
#include "../yvalve/array_proto.h"
#include "../yvalve/blob_proto.h"
#include "../yvalve/utl_proto.h"
#include "../yvalve/why_proto.h"
#include "../yvalve/MasterImplementation.h"
#include "../yvalve/PluginManager.h"
#include "../jrd/acl.h"
#include "../jrd/align.h"
#include "firebird/impl/blr.h"
#include "../common/msg_encode.h"
#include "firebird/impl/inf_pub.h"
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
#include <functional>
using namespace Firebird;
using namespace Why;
static void badHandle(ISC_STATUS code);
static bool isNetworkError(const IStatus* status);
static void nullCheck(const FB_API_HANDLE* ptr, ISC_STATUS code);
static void badSqldaVersion(const short version);
static int sqldaTruncateString(char* buffer, FB_SIZE_T size, const char* s);
static void sqldaDescribeParameters(XSQLDA* sqlda, IMessageMetadata* parameters);
static ISC_STATUS openOrCreateBlob(ISC_STATUS* userStatus, isc_db_handle* dbHandle,
isc_tr_handle* traHandle, isc_blob_handle* blobHandle, ISC_QUAD* blobId,
USHORT bpbLength, const UCHAR* bpb, bool createFlag);
//-------------------------------------
static const USHORT PREPARE_BUFFER_SIZE = 32768; // size of buffer used in isc_dsql_prepare call
static const USHORT DESCRIBE_BUFFER_SIZE = 1024; // size of buffer used in isc_dsql_describe_xxx call
namespace Why {
class StatusVector;
extern UtilInterface utilInterface;
static bool isShutdownStarted();
};
namespace {
static const struct {
int fac_code;
const char* facility;
} facilities[] = {
{FB_IMPL_MSG_FACILITY_JRD, "JRD "},
{FB_IMPL_MSG_FACILITY_GFIX, "GFIX "},
{FB_IMPL_MSG_FACILITY_DSQL, "DSQL "},
{FB_IMPL_MSG_FACILITY_DYN, "DYN "},
{FB_IMPL_MSG_FACILITY_GBAK, "GBAK "},
{FB_IMPL_MSG_FACILITY_SQLERR, "SQLERR "},
{FB_IMPL_MSG_FACILITY_GSEC, "GSEC "},
{FB_IMPL_MSG_FACILITY_GSTAT, "GSTAT "},
{FB_IMPL_MSG_FACILITY_FBSVCMGR, "FBSVCMGR "},
{FB_IMPL_MSG_FACILITY_UTL, "UTL "},
{FB_IMPL_MSG_FACILITY_NBACKUP, "NBACKUP "},
{FB_IMPL_MSG_FACILITY_FBTRACEMGR, "FBTRACEMGR"},
{0, NULL}
};
// Class-wrapper around external SQLDA.
// Can be used as local variable, but do it with care
class SQLDAMetadata final :
public RefCntIface<IMessageMetadataImpl<SQLDAMetadata, CheckStatusWrapper> >
{
friend class SQLDAMetadataLauncher;
private:
int detach(); // is called from launcher class when it goes off
// Fool-proof requested by Alex
// Private memory operators to be sure that this class is used in heap only with launcher
void* operator new (size_t s, Firebird::MemoryPool& pool ALLOC_PARAMS) { return pool.allocate(s ALLOC_PASS_ARGS); }
void operator delete (void* mem, Firebird::MemoryPool& ALLOC_PARAMS) { MemoryPool::globalFree(mem); }
void operator delete (void* mem) { MemoryPool::globalFree(mem); }
public:
typedef UCharBuffer DataBuffer;
SQLDAMetadata(const XSQLDA* aSqlda);
~SQLDAMetadata() { delete[] offsets; }
unsigned getCount(CheckStatusWrapper* status);
const char* getField(CheckStatusWrapper* status, unsigned index);
const char* getRelation(CheckStatusWrapper* status, unsigned index);
const char* getOwner(CheckStatusWrapper* status, unsigned index);
const char* getAlias(CheckStatusWrapper* status, unsigned index);
unsigned getType(CheckStatusWrapper* status, unsigned index);
FB_BOOLEAN isNullable(CheckStatusWrapper* status, unsigned index);
int getSubType(CheckStatusWrapper* status, unsigned index);
unsigned getLength(CheckStatusWrapper* status, unsigned index);
int getScale(CheckStatusWrapper* status, unsigned index);
unsigned getCharSet(CheckStatusWrapper* status, unsigned index);
unsigned getOffset(CheckStatusWrapper* status, unsigned index);
unsigned getNullOffset(CheckStatusWrapper* status, unsigned index);
IMetadataBuilder* getBuilder(CheckStatusWrapper* status);
unsigned getMessageLength(CheckStatusWrapper* status);
unsigned getAlignment(CheckStatusWrapper* status);
unsigned getAlignedLength(CheckStatusWrapper* status);
void gatherData(DataBuffer& to); // Copy data from SQLDA into target buffer.
void scatterData(DataBuffer& from);
private:
void assign(); // copy metadata from sqlda and calculate length and offsets
const XSQLDA* sqlda;
unsigned count;
// Internal structure to copy metadata from sqlda
struct OffsetItem
{
unsigned type;
int subType;
unsigned length;
int scale;
unsigned charSet;
unsigned offset;
unsigned indOffset;
} *offsets;
unsigned length, alignment;
bool speedHackEnabled; // May be user by stupid luck use right buffer format even with SQLDA interface?..
};
// Initial owner for SQLDAMetadata. It must not live longer that XSQLDA it is created for is know to be valid and fixed.
// Mostly it means that instance of this class has to be a local variable at the same or nested level with the original XSQLDA*.
// When launcher is dying, the rocket must either die too or switch to internal sources and take off
// Using of this class brings overhead of dynamic memory and pointers, but with current architecture (reference counted interfaces
// only plain buffers) - inevitable.
class SQLDAMetadataLauncher
{
public:
SQLDAMetadata* metadata;
explicit SQLDAMetadataLauncher(const XSQLDA* sqlda) : metadata(NULL)
{
if (sqlda)
{
metadata = FB_NEW SQLDAMetadata(sqlda);
metadata->addRef();
}
}
~SQLDAMetadataLauncher()
{
if (metadata)
metadata->detach();
}
UCHAR* getBuffer(); // Provide empty data buffer with the same live time
void gatherData(SQLDAMetadata::DataBuffer& to)
{
if (metadata)
metadata->gatherData(to);
else
to.clear();
}
void scatterData()
{
if (metadata)
metadata->scatterData(buffer);
}
private:
// Private operator new prevents this class from being allocated in heap, so it can be used only as stack or static variable
void* operator new (size_t);
SQLDAMetadata::DataBuffer buffer;
};
SQLDAMetadata::SQLDAMetadata(const XSQLDA* aSqlda)
: sqlda(aSqlda), count(0), offsets(NULL), length(0), alignment(0), speedHackEnabled(false)
{
if (sqlda && sqlda->version != SQLDA_VERSION1)
{
badSqldaVersion(sqlda->version);
}
}
unsigned SQLDAMetadata::getCount(CheckStatusWrapper* status)
{
if (sqlda)
return sqlda->sqld;
return count;
}
const char* SQLDAMetadata::getField(CheckStatusWrapper* status, unsigned index)
{
if (sqlda)
{
fb_assert(sqlda->sqld > (int)index);
return sqlda->sqlvar[index].sqlname;
}
// we are in free fly. It is only possible for input sqlda which usually have no names inside
return ""; // Old conversion sqlda->BLR->metadata dropped them anyway
}
const char* SQLDAMetadata::getRelation(CheckStatusWrapper* status, unsigned index)
{
if (sqlda)
{
fb_assert(sqlda->sqld > (int)index);
return sqlda->sqlvar[index].relname;
}
return "";
}
const char* SQLDAMetadata::getOwner(CheckStatusWrapper* status, unsigned index)
{
if (sqlda)
{
fb_assert(sqlda->sqld > (int) index);
return sqlda->sqlvar[index].ownname;
}
return "";
}
const char* SQLDAMetadata::getAlias(CheckStatusWrapper* status, unsigned index)
{
if (sqlda)
{
fb_assert(sqlda->sqld > (int) index);
return sqlda->sqlvar[index].aliasname;
}
return "";
}
unsigned SQLDAMetadata::getType(CheckStatusWrapper* status, unsigned index)
{
if (offsets)
{
fb_assert(count > index);
return offsets[index].type & ~1;
}
if (sqlda)
{
fb_assert(sqlda->sqld > (int) index);
return sqlda->sqlvar[index].sqltype & ~1;
}
fb_assert(false);
return 0;
}
FB_BOOLEAN SQLDAMetadata::isNullable(CheckStatusWrapper* status, unsigned index)
{
if (offsets)
{
fb_assert(count > index);
return offsets[index].type & 1;
}
if (sqlda)
{
fb_assert(sqlda->sqld > (int) index);
return sqlda->sqlvar[index].sqltype & 1;
}
fb_assert(false);
return FB_FALSE;
}
int SQLDAMetadata::getSubType(CheckStatusWrapper* status, unsigned index)
{
if (offsets)
{
fb_assert(count > index);
return offsets[index].subType;
}
if (sqlda)
{
fb_assert(sqlda->sqld > (int) index);
ISC_SHORT sqltype = sqlda->sqlvar[index].sqltype & ~1;
if (sqltype == SQL_VARYING || sqltype == SQL_TEXT)
return sqlda->sqlvar[index].sqlsubtype == CS_BINARY ? fb_text_subtype_binary : fb_text_subtype_text;
return sqlda->sqlvar[index].sqlsubtype;
}
fb_assert(false);
return 0;
}
unsigned SQLDAMetadata::getLength(CheckStatusWrapper* status, unsigned index)
{
if (offsets)
{
fb_assert(count > index);
return offsets[index].length;
}
if (sqlda)
{
fb_assert(sqlda->sqld > (int) index);
return sqlda->sqlvar[index].sqllen;
}
fb_assert(false);
return 0;
}
int SQLDAMetadata::getScale(CheckStatusWrapper* status, unsigned index)
{
if (offsets)
{
fb_assert(count > index);
return offsets[index].scale;
}
if (sqlda)
{
fb_assert(sqlda->sqld > (int) index);
if ((sqlda->sqlvar[index].sqltype & ~1) == SQL_BLOB)
return 0;
return sqlda->sqlvar[index].sqlscale;
}
fb_assert(false);
return 0;
}
unsigned SQLDAMetadata::getCharSet(CheckStatusWrapper* status, unsigned index)
{
if (offsets)
{
fb_assert(count > index);
return offsets[index].charSet;
}
if (sqlda)
{
fb_assert(sqlda->sqld > (int) index);
switch (sqlda->sqlvar[index].sqltype & ~1)
{
case SQL_TEXT:
case SQL_VARYING:
return sqlda->sqlvar[index].sqlsubtype;
case SQL_BLOB:
return sqlda->sqlvar[index].sqlscale;
default:
return 0;
}
}
fb_assert(false);
return 0;
}
unsigned SQLDAMetadata::getOffset(CheckStatusWrapper* status, unsigned index)
{
if (!offsets)
assign();
fb_assert(count > index);
return offsets[index].offset;
}
unsigned SQLDAMetadata::getNullOffset(CheckStatusWrapper* status, unsigned index)
{
if (!offsets)
assign();
fb_assert(count > index);
return offsets[index].indOffset;
}
// ATTENTION!!! Keep this method in sync with MsgMetadata::MakeOffsets()
void SQLDAMetadata::assign()
{
if (offsets)
return; // already assigned
if (sqlda->sqld <= 0) // malformed sqlda?
return;
count = (USHORT) sqlda->sqld;
speedHackEnabled = true; // May be we are lucky...
ISC_SCHAR* const base = sqlda->sqlvar[0].sqldata;
offsets = FB_NEW OffsetItem[count];
for (unsigned i = 0; i < count; i++)
{
const XSQLVAR& var = sqlda->sqlvar[i];
OffsetItem& it = offsets[i];
it.type = var.sqltype;
it.subType = var.sqlsubtype;
it.length = var.sqllen;
it.scale = var.sqlscale;
switch (var.sqltype & ~1)
{
case SQL_TEXT:
case SQL_VARYING:
it.charSet = var.sqlsubtype;
it.subType = 0;
break;
case SQL_BLOB:
it.charSet = var.sqlscale;
it.scale = 0;
break;
default:
it.charSet = 0;
}
// No matter how good or bad is the way data is placed in message buffer, it cannot be changed
// because changing of it on current codebase will completely kill remote module and may be the engine as well
unsigned dtype;
length = fb_utils::sqlTypeToDsc(length, var.sqltype, var.sqllen,
&dtype, NULL /*length*/, &it.offset, &it.indOffset);
if (it.offset != var.sqldata - base || it.indOffset != ((ISC_SCHAR*) (var.sqlind)) - base)
speedHackEnabled = false; // No luck
if (dtype < DTYPE_TYPE_MAX)
alignment = MAX(alignment, type_alignments[dtype]);
}
}
unsigned SQLDAMetadata::getMessageLength(CheckStatusWrapper* status)
{
if (!offsets)
assign();
return length;
}
unsigned SQLDAMetadata::getAlignment(CheckStatusWrapper* status)
{
if (!offsets)
assign();
return alignment;
}
unsigned SQLDAMetadata::getAlignedLength(CheckStatusWrapper* status)
{
if (!offsets)
assign();
return FB_ALIGN(length, alignment);
}
void SQLDAMetadata::gatherData(DataBuffer& to)
{
fb_assert(sqlda); // Ensure that data is gathered before take off because later they can be already changed
if (sqlda->sqld <= 0)
{
to.clear();
return;
}
const unsigned l = getMessageLength(NULL);
if (speedHackEnabled)
{
to.assign(reinterpret_cast<UCHAR*>(sqlda->sqlvar[0].sqldata), l);
return;
}
UCHAR* result = to.getBuffer(l, false);
for (unsigned i = 0; i < count; i++)
{
SSHORT* nullInd = (SSHORT*)(result + offsets[i].indOffset);
UCHAR* data = result + offsets[i].offset;
const XSQLVAR& var = sqlda->sqlvar[i];
unsigned len = var.sqllen;
if ((var.sqltype & ~1) == SQL_VARYING)
len += sizeof(USHORT);
if (var.sqltype & 1)
{
// Make sure user has specified a location for null indicator.
if (!var.sqlind)
{
(Arg::Gds(isc_dsql_sqlda_value_err) <<
Arg::Gds(isc_dsql_no_sqlind) <<
Arg::Gds(isc_dsql_sqlvar_index) << Arg::Num(i)
).raise();
}
*nullInd = *var.sqlind;
}
else
*nullInd = 0;
// Make sure user has specified a data location (unless NULL).
if (!var.sqldata && !*nullInd && (var.sqltype & ~1) != SQL_NULL)
{
(Arg::Gds(isc_dsql_sqlda_value_err) <<
Arg::Gds(isc_dsql_no_sqldata) <<
Arg::Gds(isc_dsql_sqlvar_index) << Arg::Num(i)
).raise();
}
// This is assertion instead of error check because such situation is next to impossible: buffer size is calculated a routine above
fb_assert(data + len < result + length);
// Copy data - unless known to be NULL.
if (!*nullInd)
memcpy(data, var.sqldata, len);
}
}
void SQLDAMetadata::scatterData(DataBuffer& from)
{
fb_assert(sqlda);
///fb_assert(offsets); // Not reliable, but still check that input buffer can come from this metadata
if (speedHackEnabled)
return; // Data is already in user's buffer
fb_assert(length == from.getCount());
for (unsigned i = 0; i < count; i++)
{
const XSQLVAR& var = sqlda->sqlvar[i];
if ((var.sqltype & ~1) != SQL_NULL)
{
unsigned len = var.sqllen;
// Make sure user has specified a data location.
if (!var.sqldata)
{
(Arg::Gds(isc_dsql_sqlda_value_err) <<
Arg::Gds(isc_dsql_no_sqldata) <<
Arg::Gds(isc_dsql_sqlvar_index) << Arg::Num(i)
).raise();
}
if ((var.sqltype & ~1) == SQL_VARYING)
len += sizeof(SSHORT);
memcpy(var.sqldata, from.begin() + offsets[i].offset, len);
}
if (var.sqltype & 1)
{
// Make sure user has specified a location for null indicator.
if (!var.sqlind)
{
(Arg::Gds(isc_dsql_sqlda_value_err) <<
Arg::Gds(isc_dsql_no_sqlind) <<
Arg::Gds(isc_dsql_sqlvar_index) << Arg::Num(i)
).raise();
}
*var.sqlind = *reinterpret_cast<ISC_SHORT*>(from.begin() + offsets[i].indOffset);
}
}
}
UCHAR* SQLDAMetadataLauncher::getBuffer()
{
if (metadata)
{
// ASF: It's important to call getMessageLength before check speedHackEnabled.
unsigned length = metadata->getMessageLength(NULL);
if (metadata->speedHackEnabled)
return reinterpret_cast<UCHAR*>(metadata->sqlda->sqlvar[0].sqldata);
return buffer.getBuffer(length, false);
}
else
{
buffer.clear();
return NULL;
}
}
IMetadataBuilder* SQLDAMetadata::getBuilder(CheckStatusWrapper* status)
{
// no way to construct SQLDA
fb_assert(false);
return NULL;
}
int SQLDAMetadata::detach()
{
// This code can lead to unnecessary work but not to segfault
if (refCounter.value() > 1)
{
if (!offsets) // in current codebase this is never true because offsets are allocated on buffer size calculation
assign();
}
sqlda = NULL;
speedHackEnabled = false;
return release();
}
GlobalPtr<RWLock> handleMappingLock;
GlobalPtr<GenericMap<Pair<NonPooled<isc_svc_handle, YService*> > > > services;
GlobalPtr<GenericMap<Pair<NonPooled<isc_db_handle, YAttachment*> > > > attachments;
GlobalPtr<GenericMap<Pair<NonPooled<FB_API_HANDLE, YEvents*> > > > events;
GlobalPtr<GenericMap<Pair<NonPooled<isc_tr_handle, YTransaction*> > > > transactions;
GlobalPtr<GenericMap<Pair<NonPooled<isc_stmt_handle, IscStatement*> > > > statements;
GlobalPtr<GenericMap<Pair<NonPooled<isc_req_handle, YRequest*> > > > requests;
GlobalPtr<GenericMap<Pair<NonPooled<isc_blob_handle, YBlob*> > > > blobs;
//-------------------------------------
// CVC: I'm following types_pub.h here. If there's a better solution, commit it, please.
#if defined(_LP64) || defined(__LP64__) || defined(__arch64__) || defined(_WIN64)
inline FB_API_HANDLE ULONG_TO_FB_API_HANDLE(ULONG h) { return static_cast<FB_API_HANDLE>(h); }
inline ULONG FB_API_HANDLE_TO_ULONG(FB_API_HANDLE h) { return h; }
#else
inline FB_API_HANDLE ULONG_TO_FB_API_HANDLE(ULONG h) { return reinterpret_cast<FB_API_HANDLE>(h); }
inline ULONG FB_API_HANDLE_TO_ULONG(FB_API_HANDLE h) { return reinterpret_cast<ULONG>(h); }
#endif
template <typename T>
void makeHandle(GenericMap<Pair<NonPooled<FB_API_HANDLE, T*> > >* map, T* obj, FB_API_HANDLE& h)
{
static ULONG sequenceNumber = 0;
WriteLockGuard sync(handleMappingLock, FB_FUNCTION);
if (h) // Avoid 2 different handles for same object
return;
ULONG handle = 0;
// Loop until we find an empty handle slot. This is to care of case when counter rolls over.
do
{
// Generate handle number using rolling counter.
// This way we tend to give out unique handle numbers and closed
// handles do not appear as valid to our clients.
handle = ++sequenceNumber;
// Avoid generating NULL handle when sequence number wraps
if (!handle)
handle = ++sequenceNumber;
} while (map->put(ULONG_TO_FB_API_HANDLE(handle), obj));
h = ULONG_TO_FB_API_HANDLE(handle);
}
template <typename T>
void removeHandle(GenericMap<Pair<NonPooled<FB_API_HANDLE, T*> > >* map, FB_API_HANDLE& handle)
{
if (handle)
{
WriteLockGuard sync(handleMappingLock, FB_FUNCTION);
bool removed = map->remove(handle);
fb_assert(removed);
(void) removed; // avoid warning in prod build
handle = 0;
}
}
template <typename T>
RefPtr<T> translateHandle(GlobalPtr<GenericMap<Pair<NonPooled<FB_API_HANDLE, T*> > > >& map,
FB_API_HANDLE* handle)
{
if (!handle)
status_exception::raise(Arg::Gds(T::ERROR_CODE));
ReadLockGuard sync(handleMappingLock, FB_FUNCTION);
T** obj = map->get(*handle);
if (!obj)
status_exception::raise(Arg::Gds(T::ERROR_CODE));
return RefPtr<T>(*obj);
}
//-------------------------------------
const int SHUTDOWN_TIMEOUT = 10000; // 10 sec
class ShutdownInit
{
public:
explicit ShutdownInit(MemoryPool&)
{
InstanceControl::registerShutdown(atExitShutdown);
}
private:
static void atExitShutdown()
{
if (MasterInterfacePtr()->getProcessExiting())
InstanceControl::cancelCleanup();
else
fb_shutdown(SHUTDOWN_TIMEOUT, fb_shutrsn_exit_called);
}
};
#ifdef UNIX
int killed;
bool procInt, procTerm;
SignalSafeSemaphore* shutdownSemaphore = NULL;
THREAD_ENTRY_DECLARE shutdownThread(THREAD_ENTRY_PARAM)
{
for (;;)
{
killed = 0;
try
{
if (shutdownSemaphore)
shutdownSemaphore->enter();
}
catch (status_exception& e)
{
TEXT buffer[BUFFER_LARGE];
const ISC_STATUS* vector = e.value();
if (! (vector && fb_interpret(buffer, sizeof(buffer), &vector)))
strcpy(buffer, "Unknown failure in shutdown thread in shutdownSemaphore->enter()");
fb_utils::logAndDie(buffer);
}
if (!killed)
break;
// perform shutdown
if (fb_shutdown(SHUTDOWN_TIMEOUT, fb_shutrsn_signal) == FB_SUCCESS)
{
InstanceControl::registerShutdown(0);
break; //exit(0);
}
}
return 0;
}
void handler(int sig)
{
if (!killed && shutdownSemaphore)
{
killed = sig;
shutdownSemaphore->release();
}
}
void handlerInt(void*)
{
handler(SIGINT);
}
void handlerTerm(void*)
{
handler(SIGTERM);
}
class CtrlCHandler : public ShutdownInit
{
public:
SignalSafeSemaphore semaphore;
explicit CtrlCHandler(MemoryPool& p)
: ShutdownInit(p)
{
Thread::start(shutdownThread, 0, 0, &handle);
procInt = ISC_signal(SIGINT, handlerInt, 0);
procTerm = ISC_signal(SIGTERM, handlerTerm, 0);
shutdownSemaphore = &semaphore;
}
~CtrlCHandler()
{
ISC_signal_cancel(SIGINT, handlerInt, 0);
ISC_signal_cancel(SIGTERM, handlerTerm, 0);
if (!killed)
{
// Must be done to let shutdownThread close.
shutdownSemaphore->release();
shutdownSemaphore = NULL;
Thread::waitForCompletion(handle);
}
}
private:
Thread::Handle handle;
};
#endif // UNIX
void signalInit()
{
#ifdef UNIX
static GlobalPtr<CtrlCHandler> ctrlCHandler;
#else
static GlobalPtr<ShutdownInit> shutdownInit;
#endif // UNIX
}
} // anonymous namespace
//-------------------------------------
namespace Why
{
// StatusVector: Provides correct status vector for operation and init() it.
class StatusVector : public AutoIface<BaseStatus<StatusVector> >
{
public:
explicit StatusVector(ISC_STATUS* v = NULL) throw()
: localVector(v ? v : localStatus)
{ }
operator const ISC_STATUS*()
{
merge();
return localVector;
}
~StatusVector()
{
merge();
#ifdef DEV_BUILD
checkStatusVector(localVector);
#endif
}
// IStatus implementation
void dispose()
{ }
#ifdef DEV_BUILD
// Validate that a status vector looks valid.
static void checkStatusVector(const ISC_STATUS* status)
{
#define SV_MSG(x) \
do { \
gds__log ("%s %d check_status_vector: %s", __FILE__, __LINE__, (x)); BREAKPOINT (__LINE__); \
} while (false)
const ISC_STATUS* s = status;
if (!s)
{
SV_MSG("Invalid status vector");
return;
}
if (*s != isc_arg_gds)
{
SV_MSG("Must start with isc_arg_gds");
return;
}
// Vector [2] could either end the vector, or start a warning
// in either case the status vector is a success.
if (s[1] == FB_SUCCESS && s[2] != isc_arg_end && s[2] != isc_arg_gds &&
s[2] != isc_arg_warning)
{
SV_MSG("Bad success vector format");
}
ULONG length;
while (*s != isc_arg_end)
{
const ISC_STATUS code = *s++;
switch (code)
{
case isc_arg_warning:
case isc_arg_gds:
// The next element must either be 0 (indicating no error) or a
// valid isc error message, let's check.
if (*s && (*s & ISC_MASK) != ISC_MASK)
{
if (code == isc_arg_warning)
SV_MSG("warning code not a valid ISC message");
else
SV_MSG("error code not a valid ISC message");
}
// If the error code is valid, then I better be able to retrieve a
// proper facility code from it ... let's find out.
if (*s && (*s & ISC_MASK) == ISC_MASK)
{
bool found = false;
const auto* facs = facilities;
const int fac_code = GET_FACILITY(*s);
while (facs->facility)
{
if (facs->fac_code == fac_code)
{
found = true;
break;
}
++facs;
}
if (!found)
{
if (code == isc_arg_warning)
SV_MSG("warning code does not contain a valid facility");
else
SV_MSG("error code does not contain a valid facility");
}
}
++s;
break;
case isc_arg_interpreted:
case isc_arg_string:
case isc_arg_sql_state:
length = static_cast<ULONG>(strlen((const char*) *s));
// This check is heuristic, not deterministic.
if (length > 1024 - 1)
SV_MSG("suspect length value");
if (*((const UCHAR*) *s) == 0xCB)
SV_MSG("string in freed memory");
++s;
break;
case isc_arg_cstring:
length = (ULONG) *s;
++s;
// This check is heuristic, not deterministic.
// Note: This can never happen anyway, as the length is coming from a byte value.
if (length > 1024 - 1)