/
jrd.cpp
9432 lines (7811 loc) · 218 KB
/
jrd.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: jrd.cpp
* DESCRIPTION: User visible entrypoints
*
* 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): ______________________________________.
*
* 2001.07.06 Sean Leyne - Code Cleanup, removed "#ifdef READONLY_DATABASE"
* conditionals, as the engine now fully supports
* readonly databases.
* 2001.07.09 Sean Leyne - Restore default setting to Force Write = "On", for
* Windows NT platform, for new database files. This was changed
* with IB 6.0 to OFF and has introduced many reported database
* corruptions.
*
* 2002.10.29 Sean Leyne - Removed obsolete "Netware" port
* Claudio Valderrama C.
* Adriano dos Santos Fernandes
*
*/
#include "firebird.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "../common/ThreadStart.h"
#include <stdarg.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_PWD_H
#include <pwd.h>
#endif
#include <errno.h>
#include "../jrd/EngineInterface.h"
#include "../jrd/jrd.h"
#include "../jrd/irq.h"
#include "../jrd/drq.h"
#include "../jrd/req.h"
#include "../jrd/tra.h"
#include "../jrd/blb.h"
#include "../jrd/lck.h"
#include "../jrd/nbak.h"
#include "../jrd/scl.h"
#include "../jrd/os/pio.h"
#include "../jrd/ods.h"
#include "../jrd/exe.h"
#include "../jrd/extds/ExtDS.h"
#include "../jrd/val.h"
#include "../jrd/rse.h"
#include "../jrd/intl.h"
#include "../jrd/sbm.h"
#include "../jrd/svc.h"
#include "../jrd/sdw.h"
#include "../jrd/lls.h"
#include "../jrd/cch.h"
#include "../intl/charsets.h"
#include "../jrd/sort.h"
#include "../jrd/PreparedStatement.h"
#include "../jrd/ResultSet.h"
#include "../dsql/StmtNodes.h"
#include "../jrd/blb_proto.h"
#include "../jrd/cch_proto.h"
#include "../jrd/cmp_proto.h"
#include "../jrd/err_proto.h"
#include "../jrd/exe_proto.h"
#include "../jrd/ext_proto.h"
#include "../jrd/fun_proto.h"
#include "../yvalve/gds_proto.h"
#include "../jrd/inf_proto.h"
#include "../jrd/ini_proto.h"
#include "../jrd/intl_proto.h"
#include "../common/isc_f_proto.h"
#include "../common/isc_proto.h"
#include "../jrd/jrd_proto.h"
#include "../jrd/lck_proto.h"
#include "../jrd/met_proto.h"
#include "../jrd/mov_proto.h"
#include "../jrd/opt_proto.h"
#include "../jrd/pag_proto.h"
#include "../jrd/par_proto.h"
#include "../jrd/os/pio_proto.h"
#include "../jrd/scl_proto.h"
#include "../jrd/sdw_proto.h"
#include "../jrd/shut_proto.h"
#include "../jrd/tpc_proto.h"
#include "../jrd/tra_proto.h"
#include "../jrd/val_proto.h"
#include "../jrd/validation.h"
#include "../jrd/vio_proto.h"
#include "../jrd/dfw_proto.h"
#include "../common/file_params.h"
#include "../jrd/event_proto.h"
#include "../yvalve/why_proto.h"
#include "../jrd/flags.h"
#include "../jrd/Mapping.h"
#include "../jrd/Database.h"
#include "../common/config/config.h"
#include "../common/config/dir_list.h"
#include "../common/db_alias.h"
#include "../jrd/replication/Publisher.h"
#include "../jrd/replication/Applier.h"
#include "../jrd/trace/TraceManager.h"
#include "../jrd/trace/TraceObjects.h"
#include "../jrd/trace/TraceJrdHelpers.h"
#include "../jrd/IntlManager.h"
#include "../common/classes/fb_tls.h"
#include "../common/classes/ClumpletWriter.h"
#include "../common/classes/RefMutex.h"
#include "../common/classes/ParsedList.h"
#include "../common/utils_proto.h"
#include "../jrd/DebugInterface.h"
#include "../jrd/CryptoManager.h"
#include "../jrd/DbCreators.h"
#include "../dsql/dsql.h"
#include "../dsql/dsql_proto.h"
#include "../dsql/DsqlBatch.h"
#ifdef WIN_NT
#include "../common/dllinst.h"
#endif
using namespace Jrd;
using namespace Firebird;
const SSHORT WAIT_PERIOD = -1;
#ifdef SUPPORT_RAW_DEVICES
#define unlink PIO_unlink
#endif
#ifdef DEV_BUILD
int debug;
#endif
namespace Jrd
{
int JBlob::release()
{
if (--refCounter != 0)
return 1;
if (blob)
{
LocalStatus status;
CheckStatusWrapper statusWrapper(&status);
freeEngineData(&statusWrapper);
}
if (blob)
{
// normal cleanup failed, take minimum precautions before deleting JBlob
blob->blb_interface = NULL;
blob = NULL;
}
delete this;
return 0;
}
int JTransaction::release()
{
if (--refCounter != 0)
return 1;
RefDeb(DEB_RLS_JATT, "JTransaction::release");
if (transaction)
{
LocalStatus status;
CheckStatusWrapper statusWrapper(&status);
freeEngineData(&statusWrapper);
}
if (transaction)
{
fb_assert(!(transaction->tra_flags & TRA_own_interface));
transaction->tra_flags |= TRA_own_interface;
addRef();
}
else
delete this;
return 0;
}
int JStatement::release()
{
if (--refCounter != 0)
return 1;
if (statement)
{
LocalStatus status;
CheckStatusWrapper statusWrapper(&status);
freeEngineData(&statusWrapper);
}
delete this;
return 0;
}
int JRequest::release()
{
if (--refCounter != 0)
return 1;
if (rq)
{
LocalStatus status;
CheckStatusWrapper statusWrapper(&status);
freeEngineData(&statusWrapper);
}
delete this;
return 0;
}
int JEvents::release()
{
if (--refCounter != 0)
return 1;
if (id >= 0)
{
LocalStatus status;
CheckStatusWrapper statusWrapper(&status);
freeEngineData(&statusWrapper);
}
delete this;
return 0;
}
JAttachment::JAttachment(StableAttachmentPart* sa)
: att(sa)
{
}
Attachment* JAttachment::getHandle() throw()
{
return att ? att->getHandle() : NULL;
}
const Attachment* JAttachment::getHandle() const throw()
{
return att ? att->getHandle() : NULL;
}
//#define DEBUG_ATT_COUNTERS
void JAttachment::addRef()
{
int v = ++refCounter;
#ifdef DEBUG_ATT_COUNTERS
ReferenceCounterDebugger* my = ReferenceCounterDebugger::get(DEB_AR_JATT);
const char* point = my ? my->rcd_point : " <Unknown> ";
fprintf(stderr, "addRef from <%s> att %p cnt=%d\n", point, this, v);
#endif
}
int JAttachment::release()
{
#ifdef DEV_BUILD
int r = --refCounter;
#ifdef DEBUG_ATT_COUNTERS
ReferenceCounterDebugger* my = ReferenceCounterDebugger::get(DEB_RLS_JATT);
const char* point = my ? my->rcd_point : " <Unknown> ";
fprintf(stderr, "Release from <%s> att %p cnt=%d\n", point, this, r);
#endif
if (r != 0)
return r;
#else
if (--refCounter != 0)
return 1;
#endif
if (att)
{
LocalStatus status;
CheckStatusWrapper statusWrapper(&status);
freeEngineData(&statusWrapper, true);
}
if (!att)
{
delete this;
}
return 0;
}
JBlob::JBlob(blb* handle, StableAttachmentPart* sa)
: blob(handle), sAtt(sa)
{
}
JTransaction::JTransaction(jrd_tra* handle, StableAttachmentPart* sa)
: transaction(handle), sAtt(sa)
{
}
JTransaction::JTransaction(JTransaction* from)
: transaction(from->transaction), sAtt(from->sAtt)
{
}
JResultSet::JResultSet(DsqlCursor* handle, JStatement* aStatement)
: cursor(handle), statement(aStatement), state(-1)
{
}
JRequest::JRequest(JrdStatement* handle, StableAttachmentPart* sa)
: rq(handle), sAtt(sa)
{
}
JEvents::JEvents(int aId, StableAttachmentPart* sa, Firebird::IEventCallback* aCallback)
: id(aId), sAtt(sa), callback(aCallback)
{
}
JStatement::JStatement(dsql_req* handle, StableAttachmentPart* sa, Firebird::Array<UCHAR>& meta)
: statement(handle), sAtt(sa), metadata(getPool(), this, sAtt)
{
metadata.parse(meta.getCount(), meta.begin());
}
JService::JService(Jrd::Service* handle)
: svc(handle)
{
}
int JService::release()
{
if (--refCounter != 0)
return 1;
if (svc)
{
LocalStatus status;
CheckStatusWrapper statusWrapper(&status);
freeEngineData(&statusWrapper);
}
if (!svc)
{
delete this;
}
return 0;
}
int JProvider::release()
{
if (--refCounter == 0)
{
delete this;
return 0;
}
return 1;
}
static void threadDetach()
{
ThreadSync* thd = ThreadSync::findThread();
delete thd;
}
static void shutdownBeforeUnload()
{
LocalStatus status;
CheckStatusWrapper statusWrapper(&status);
AutoPlugin<JProvider>(JProvider::getInstance())->shutdown(&statusWrapper, 0, fb_shutrsn_exit_called);
threadDetach();
};
class EngineFactory : public AutoIface<IPluginFactoryImpl<EngineFactory, CheckStatusWrapper> >
{
public:
// IPluginFactory implementation
IPluginBase* createPlugin(CheckStatusWrapper* status, IPluginConfig* factoryParameter)
{
try
{
if (getUnloadDetector()->unloadStarted())
{
Arg::Gds(isc_shutdown).raise();
}
IPluginBase* p = FB_NEW JProvider(factoryParameter);
p->addRef();
return p;
}
catch (const Firebird::Exception& ex)
{
ex.stuffException(status);
}
return NULL;
}
};
static Static<EngineFactory> engineFactory;
//-------------------------------
void registerEngine(IPluginManager* iPlugin)
{
UnloadDetectorHelper* module = getUnloadDetector();
module->setCleanup(shutdownBeforeUnload);
module->setThreadDetach(threadDetach);
iPlugin->registerPluginFactory(IPluginManager::TYPE_PROVIDER, CURRENT_ENGINE, &engineFactory);
module->registerMe();
}
} // namespace Jrd
extern "C" void FB_EXPORTED FB_PLUGIN_ENTRY_POINT(IMaster* master)
{
CachedMasterInterface::set(master);
registerEngine(PluginManagerInterfacePtr());
}
namespace
{
using Jrd::Attachment;
// Flag engineShutdown guarantees that no new attachment is created after setting it
// and helps avoid more than 1 shutdown threads running simultaneously.
bool engineShutdown = false;
// This flag is protected with 2 mutexes. shutdownMutex is taken by each shutdown thread
// (for a relatively long time). newAttachmentMutex is taken (for a short time) when
// shutdown thread is starting shutdown and also when new attachment is created.
GlobalPtr<Mutex> shutdownMutex, newAttachmentMutex;
// This mutex is set when new Database block is created. It's global first of all to satisfy
// SS requirement - avoid 2 Database blocks for same database (file). Also guarantees no
// half-done Database block in databases linked list. Always taken before databases_mutex.
GlobalPtr<Mutex> dbInitMutex;
Database* databases = NULL;
// This mutex protects linked list of databases
GlobalPtr<Mutex> databases_mutex;
// Holder for per-database init/fini mutex
class RefMutexUnlock
{
public:
RefMutexUnlock()
: entered(false)
{ }
explicit RefMutexUnlock(Database::ExistenceRefMutex* p)
: ref(p), entered(false)
{ }
void enter()
{
fb_assert(ref);
ref->enter();
entered = true;
}
void leave()
{
if (entered)
{
ref->leave();
entered = false;
}
}
void linkWith(Database::ExistenceRefMutex* to)
{
if (ref == to)
return;
leave();
ref = to;
}
void unlinkFromMutex()
{
linkWith(NULL);
}
Database::ExistenceRefMutex* operator->()
{
return ref;
}
bool operator!() const
{
return !ref;
}
~RefMutexUnlock()
{
leave();
}
private:
RefPtr<Database::ExistenceRefMutex> ref;
bool entered;
};
// We have 2 more related types of mutexes in database and attachment.
// Attachment is using reference counted mutex in JAtt, also making it possible
// to check does object still exist after locking a mutex. This makes great use when
// checking for correctness of attachment in provider's entrypoints. Attachment mutex
// is always taken before database's mutex and (except when new attachment is created)
// when entering inside provider and releases when waiting for something or when rescheduling.
// Database mutex (dbb_sync) is taken when access to database-wide data (like list of
// attachments) is accessed. No other mutex from above mentioned here can be taken after
// dbb_sync with an exception of attachment mutex for new attachment.
// So finally the order of taking mutexes is:
// 1. dbInitMutex (in attach/create database) or attachment mutex in other entries
// 2. databases_mutex (when / if needed)
// 3. dbb_sync (when / if needed)
// 4. only for new attachments: attachment mutex when that attachment is created
// Any of this may be missing when not needed, but order of taking should not be changed.
class EngineStartup
{
public:
static void init()
{
IbUtil::initialize();
IntlManager::initialize();
ExtEngineManager::initialize();
}
static void cleanup()
{
}
};
InitMutex<EngineStartup> engineStartup("EngineStartup");
class OverwriteHolder : public MutexLockGuard
{
public:
explicit OverwriteHolder(Database* to_remove)
: MutexLockGuard(databases_mutex, FB_FUNCTION), dbb(to_remove)
{
if (!dbb)
return;
for (Database** d_ptr = &databases; *d_ptr; d_ptr = &(*d_ptr)->dbb_next)
{
if (*d_ptr == dbb)
{
*d_ptr = dbb->dbb_next;
dbb->dbb_next = NULL;
return;
}
}
fb_assert(!dbb);
dbb = NULL;
}
~OverwriteHolder()
{
if (dbb)
{
dbb->dbb_next = databases;
databases = dbb;
}
}
private:
Database* dbb;
};
inline void validateHandle(thread_db* tdbb, Jrd::Attachment* const attachment)
{
if (attachment && attachment == tdbb->getAttachment())
return;
if (!attachment || !attachment->att_database)
status_exception::raise(Arg::Gds(isc_bad_db_handle));
tdbb->setAttachment(attachment);
tdbb->setDatabase(attachment->att_database);
}
inline void validateHandle(thread_db* tdbb, jrd_tra* const transaction)
{
if (!transaction)
status_exception::raise(Arg::Gds(isc_bad_trans_handle));
validateHandle(tdbb, transaction->tra_attachment);
tdbb->setTransaction(transaction);
}
inline void validateHandle(thread_db* tdbb, JrdStatement* const statement)
{
if (!statement)
status_exception::raise(Arg::Gds(isc_bad_req_handle));
validateHandle(tdbb, statement->requests[0]->req_attachment);
}
inline void validateHandle(thread_db* tdbb, dsql_req* const statement)
{
if (!statement)
status_exception::raise(Arg::Gds(isc_bad_req_handle));
validateHandle(tdbb, statement->req_dbb->dbb_attachment);
}
inline void validateHandle(thread_db* tdbb, blb* blob)
{
if (!blob)
status_exception::raise(Arg::Gds(isc_bad_segstr_handle));
validateHandle(tdbb, blob->getTransaction());
validateHandle(tdbb, blob->getAttachment());
}
inline void validateHandle(Service* service)
{
if (!service)
status_exception::raise(Arg::Gds(isc_bad_svc_handle));
}
inline void validateHandle(thread_db* tdbb, JEvents* const events)
{
validateHandle(tdbb, events->getAttachment()->getHandle());
}
inline void validateHandle(thread_db* tdbb, DsqlCursor* const cursor)
{
if (!cursor)
status_exception::raise(Arg::Gds(isc_bad_req_handle));
validateHandle(tdbb, cursor->getTransaction());
validateHandle(tdbb, cursor->getAttachment());
}
inline void validateHandle(thread_db* tdbb, DsqlBatch* const batch)
{
if (!batch)
status_exception::raise(Arg::Gds(isc_bad_batch_handle));
validateHandle(tdbb, batch->getAttachment());
}
inline void validateHandle(thread_db* tdbb, JReplicator* const replicator)
{
if (!replicator)
status_exception::raise(Arg::Gds(isc_bad_repl_handle));
validateHandle(tdbb, replicator->getAttachment()->getHandle());
}
class AttachmentHolder
{
public:
static const unsigned ATT_LOCK_ASYNC = 1;
static const unsigned ATT_DONT_LOCK = 2;
static const unsigned ATT_NO_SHUTDOWN_CHECK = 4;
static const unsigned ATT_NON_BLOCKING = 8;
AttachmentHolder(thread_db* tdbb, StableAttachmentPart* sa, unsigned lockFlags, const char* from)
: sAtt(sa),
async(lockFlags & ATT_LOCK_ASYNC),
nolock(lockFlags & ATT_DONT_LOCK),
blocking(!(lockFlags & ATT_NON_BLOCKING))
{
if (!sa)
Arg::Gds(isc_att_shutdown).raise();
if (blocking)
sAtt->getBlockingMutex()->enter(from);
try
{
if (!nolock)
sAtt->getMutex(async)->enter(from);
Jrd::Attachment* attachment = sAtt->getHandle(); // Must be done after entering mutex
try
{
if (!attachment || (engineShutdown && !(lockFlags & ATT_NO_SHUTDOWN_CHECK)))
{
// This shutdown check is an optimization, threads can still enter engine
// with the flag set cause shutdownMutex mutex is not locked here.
// That's not a danger cause check of att_use_count
// in shutdown code makes it anyway safe.
Arg::Gds err(isc_att_shutdown);
if (sAtt->getShutError())
err << Arg::Gds(sAtt->getShutError());
err.raise();
}
tdbb->setAttachment(attachment);
tdbb->setDatabase(attachment->att_database);
if (!async)
{
attachment->att_use_count++;
attachment->setupIdleTimer(true);
}
}
catch (const Firebird::Exception&)
{
if (!nolock)
sAtt->getMutex(async)->leave();
throw;
}
}
catch (const Firebird::Exception&)
{
if (blocking)
sAtt->getBlockingMutex()->leave();
throw;
}
}
~AttachmentHolder()
{
Jrd::Attachment* attachment = sAtt->getHandle();
if (attachment && !async)
{
attachment->att_use_count--;
if (!attachment->att_use_count)
attachment->setupIdleTimer(false);
}
if (!nolock)
sAtt->getMutex(async)->leave();
if (blocking)
sAtt->getBlockingMutex()->leave();
}
private:
RefPtr<StableAttachmentPart> sAtt;
bool async; // async mutex should be locked instead normal
bool nolock; // if locked manually, no need to take lock recursively
bool blocking; // holder instance is blocking other instances
private:
// copying is prohibited
AttachmentHolder(const AttachmentHolder&);
AttachmentHolder& operator =(const AttachmentHolder&);
};
class EngineContextHolder : public ThreadContextHolder, private AttachmentHolder,
private DatabaseContextHolder
{
public:
template <typename I>
EngineContextHolder(CheckStatusWrapper* status, I* interfacePtr, const char* from,
unsigned lockFlags = 0)
: ThreadContextHolder(status),
AttachmentHolder(*this, interfacePtr->getAttachment(), lockFlags, from),
DatabaseContextHolder(operator thread_db*())
{
validateHandle(*this, interfacePtr->getHandle());
}
};
void validateAccess(thread_db* tdbb, Jrd::Attachment* attachment, SystemPrivilege sp)
{
if (!attachment->locksmith(tdbb, sp))
{
PreparedStatement::Builder sql;
MetaName missPriv("UNKNOWN");
sql << "select" << sql("rdb$type_name", missPriv) << "from rdb$types"
<< "where rdb$field_name = 'RDB$SYSTEM_PRIVILEGES'"
<< " and rdb$type =" << SSHORT(sp);
jrd_tra* transaction = attachment->getSysTransaction();
AutoPreparedStatement ps(attachment->prepareStatement(tdbb, transaction, sql));
AutoResultSet rs(ps->executeQuery(tdbb, transaction));
rs->fetch(tdbb);
UserId* u = attachment->att_user;
Arg::Gds err(isc_adm_task_denied);
err << Arg::Gds(isc_miss_prvlg) << missPriv;
if (u && u->testFlag(USR_mapdown))
err << Arg::Gds(isc_map_down);
ERR_post(err);
}
}
class DefaultCallback : public AutoIface<ICryptKeyCallbackImpl<DefaultCallback, CheckStatusWrapper> >
{
public:
unsigned int callback(unsigned int, const void*, unsigned int, void*)
{
return 0;
}
};
DefaultCallback defCallback;
ICryptKeyCallback* getDefCryptCallback(ICryptKeyCallback* callback)
{
return callback ? callback : &defCallback;
}
} // anonymous
#ifdef WIN_NT
#include <windows.h>
// these should stop a most annoying warning
#undef TEXT
#define TEXT SCHAR
#endif // WIN_NT
void Trigger::compile(thread_db* tdbb)
{
SET_TDBB(tdbb);
Database* dbb = tdbb->getDatabase();
Jrd::Attachment* const att = tdbb->getAttachment();
if (extTrigger)
return;
if (!statement)
{
compile_in_progress = true;
// Allocate statement memory pool
MemoryPool* new_pool = att->createPool();
// Trigger request is not compiled yet. Lets do it now
USHORT par_flags = (USHORT) (flags & TRG_ignore_perm) ? csb_ignore_perm : 0;
if (type & 1)
par_flags |= csb_pre_trigger;
else
par_flags |= csb_post_trigger;
try
{
Jrd::ContextPoolHolder context(tdbb, new_pool);
AutoPtr<CompilerScratch> auto_csb(FB_NEW_POOL(*new_pool) CompilerScratch(*new_pool));
CompilerScratch* csb = auto_csb;
csb->csb_g_flags |= par_flags;
if (engine.isEmpty())
{
if (debugInfo.hasData())
{
DBG_parse_debug_info((ULONG) debugInfo.getCount(), debugInfo.begin(),
*csb->csb_dbg_info);
}
PAR_blr(tdbb, relation, blr.begin(), (ULONG) blr.getCount(), NULL, &csb, &statement,
(relation ? true : false), par_flags);
}
else
{
dbb->dbb_extManager.makeTrigger(tdbb, csb, this, engine, entryPoint, extBody.c_str(),
(relation ?
(type & 1 ? IExternalTrigger::TYPE_BEFORE : IExternalTrigger::TYPE_AFTER) :
IExternalTrigger::TYPE_DATABASE));
}
}
catch (const Exception&)
{
compile_in_progress = false;
if (statement)
{
statement->release(tdbb);
statement = NULL;
}
else
att->deletePool(new_pool);
throw;
}
statement->triggerName = name;
if (ssDefiner.orElse(false))
statement->triggerInvoker = att->getUserId(owner);
if (sys_trigger)
statement->flags |= JrdStatement::FLAG_SYS_TRIGGER;
if (flags & TRG_ignore_perm)
statement->flags |= JrdStatement::FLAG_IGNORE_PERM;
compile_in_progress = false;
}
}
void Trigger::release(thread_db* tdbb)
{
if (extTrigger)
{
delete extTrigger;
extTrigger = NULL;
}
if (blr.getCount() == 0 || !statement || statement->isActive())
return;
statement->release(tdbb);
statement = NULL;
}
namespace
{
class DatabaseBindings : public CoercionArray
{
public:
DatabaseBindings(MemoryPool& p)
: CoercionArray(p)
{
// FB 2.5
versions[0].ind = getCount();
versions[0].txt = "2.5";
// bool compatibility
add().makeLegacy()->makeBoolean();
// FB 3.0
versions[1].ind = getCount();
versions[1].txt = "3.0";
// decfloat compatibility
add().makeLegacy()->makeDecimal128();
// int128 compatibility
add().makeLegacy()->makeInt128(0);
// TZ compatibility
add().makeLegacy()->makeTimestampTz();
add().makeLegacy()->makeTimeTz();
}
unsigned getCompatibilityIndex(const char* txt)
{
if (txt)
{
for (unsigned i = 0; i < FB_NELEM(versions); ++i)
{
if (strcmp(txt, versions[i].txt) == 0)
return i;
}
}
return ~0U;
}
private:
struct Version
{
unsigned ind;
const char* txt;
};
Version versions[2];
};