forked from dotnet/SqlClient
/
TdsParserStateObject.netcore.cs
3166 lines (2742 loc) · 127 KB
/
TdsParserStateObject.netcore.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.Common;
using Microsoft.Data.ProviderBase;
namespace Microsoft.Data.SqlClient
{
internal abstract partial class TdsParserStateObject
{
private static readonly ContextCallback s_readAsyncCallbackComplete = ReadAsyncCallbackComplete;
// Timeout variables
private readonly WeakReference _cancellationOwner = new WeakReference(null);
// Async
//////////////////
// Constructors //
//////////////////
internal TdsParserStateObject(TdsParser parser, TdsParserStateObject physicalConnection, bool async)
{
// Construct a MARS session
Debug.Assert(null != parser, "no parser?");
_parser = parser;
_onTimeoutAsync = OnTimeoutAsync;
SniContext = SniContext.Snix_GetMarsSession;
Debug.Assert(null != _parser._physicalStateObj, "no physical session?");
Debug.Assert(null != _parser._physicalStateObj._inBuff, "no in buffer?");
Debug.Assert(null != _parser._physicalStateObj._outBuff, "no out buffer?");
Debug.Assert(_parser._physicalStateObj._outBuff.Length ==
_parser._physicalStateObj._inBuff.Length, "Unexpected unequal buffers.");
// Determine packet size based on physical connection buffer lengths.
SetPacketSize(_parser._physicalStateObj._outBuff.Length);
CreateSessionHandle(physicalConnection, async);
if (IsFailedHandle())
{
AddError(parser.ProcessSNIError(this));
ThrowExceptionAndWarning();
}
// we post a callback that represents the call to dispose; once the
// object is disposed, the next callback will cause the GC Handle to
// be released.
IncrementPendingCallbacks();
_lastSuccessfulIOTimer = parser._physicalStateObj._lastSuccessfulIOTimer;
}
////////////////
// Properties //
////////////////
internal abstract uint DisableSsl();
internal abstract uint EnableMars(ref uint info);
internal abstract uint Status
{
get;
}
internal abstract SessionHandle SessionHandle
{
get;
}
private partial struct NullBitmap
{
internal bool TryInitialize(TdsParserStateObject stateObj, int columnsCount)
{
_columnsCount = columnsCount;
// 1-8 columns need 1 byte
// 9-16: 2 bytes, and so on
int bitmapArrayLength = (columnsCount + 7) / 8;
// allow reuse of previously allocated bitmap
if (_nullBitmap == null || _nullBitmap.Length != bitmapArrayLength)
{
_nullBitmap = new byte[bitmapArrayLength];
}
// read the null bitmap compression information from TDS
if (!stateObj.TryReadByteArray(_nullBitmap, _nullBitmap.Length))
{
return false;
}
SqlClientEventSource.Log.TryAdvancedTraceEvent("TdsParserStateObject.NullBitmap.Initialize | INFO | ADV | State Object Id {0}, NBCROW bitmap received, column count = {1}", stateObj.ObjectID, columnsCount);
SqlClientEventSource.Log.TryAdvancedTraceBinEvent("TdsParserStateObject.NullBitmap.Initialize | INFO | ADV | State Object Id {0}, NBCROW bitmap data. Null Bitmap {1}, Null bitmap length: {2}", stateObj.ObjectID, _nullBitmap, (ushort)_nullBitmap.Length);
return true;
}
}
/////////////////////
// General methods //
/////////////////////
// This method is only called by the command or datareader as a result of a user initiated
// cancel request.
internal void Cancel(object caller)
{
Debug.Assert(caller != null, "Null caller for Cancel!");
Debug.Assert(caller is SqlCommand || caller is SqlDataReader, "Calling API with invalid caller type: " + caller.GetType());
bool hasLock = false;
try
{
// Keep looping until we either grabbed the lock (and therefore sent attention) or the connection closes\breaks
while ((!hasLock) && (_parser.State != TdsParserState.Closed) && (_parser.State != TdsParserState.Broken))
{
Monitor.TryEnter(this, WaitForCancellationLockPollTimeout, ref hasLock);
if (hasLock)
{ // Lock for the time being - since we need to synchronize the attention send.
// This lock is also protecting against concurrent close and async continuations
// Ensure that, once we have the lock, that we are still the owner
if ((!_cancelled) && (_cancellationOwner.Target == caller))
{
_cancelled = true;
if (HasPendingData && !_attentionSent)
{
bool hasParserLock = false;
// Keep looping until we have the parser lock (and so are allowed to write), or the connection closes\breaks
while ((!hasParserLock) && (_parser.State != TdsParserState.Closed) && (_parser.State != TdsParserState.Broken))
{
try
{
_parser.Connection._parserLock.Wait(canReleaseFromAnyThread: false, timeout: WaitForCancellationLockPollTimeout, lockTaken: ref hasParserLock);
if (hasParserLock)
{
_parser.Connection.ThreadHasParserLockForClose = true;
SendAttention();
}
}
finally
{
if (hasParserLock)
{
if (_parser.Connection.ThreadHasParserLockForClose)
{
_parser.Connection.ThreadHasParserLockForClose = false;
}
_parser.Connection._parserLock.Release();
}
}
}
}
}
}
}
}
finally
{
if (hasLock)
{
Monitor.Exit(this);
}
}
}
private void ResetCancelAndProcessAttention()
{
// This method is shared by CloseSession initiated by DataReader.Close or completed
// command execution, as well as the session reclamation code for cases where the
// DataReader is opened and then GC'ed.
lock (this)
{
// Reset cancel state.
_cancelled = false;
_cancellationOwner.Target = null;
if (_attentionSent)
{
// Make sure we're cleaning up the AttentionAck if Cancel happened before taking the lock.
// We serialize Cancel/CloseSession to prevent a race condition between these two states.
// The problem is that both sending and receiving attentions are time taking
// operations.
Parser.ProcessPendingAck(this);
}
SetTimeoutStateStopped();
}
}
internal abstract void CreatePhysicalSNIHandle(
string serverName,
TimeoutTimer timeout,
out byte[] instanceName,
ref byte[][] spnBuffer,
bool flushCache,
bool async,
bool fParallel,
SqlConnectionIPAddressPreference iPAddressPreference,
string cachedFQDN,
ref SQLDNSInfo pendingDNSInfo,
string serverSPN,
bool isIntegratedSecurity = false,
bool tlsFirst = false,
string hostNameInCertificate = "",
string serverCertificateFilename = "");
internal abstract void AssignPendingDNSInfo(string userProtocol, string DNSCacheKey, ref SQLDNSInfo pendingDNSInfo);
internal abstract uint SniGetConnectionId(ref Guid clientConnectionId);
internal abstract bool IsFailedHandle();
protected abstract void CreateSessionHandle(TdsParserStateObject physicalConnection, bool async);
protected abstract void FreeGcHandle(int remaining, bool release);
internal abstract uint EnableSsl(ref uint info, bool tlsFirst, string serverCertificateFilename);
internal abstract uint WaitForSSLHandShakeToComplete(out int protocolVersion);
internal abstract void Dispose();
internal abstract void DisposePacketCache();
internal abstract bool IsPacketEmpty(PacketHandle readPacket);
internal abstract PacketHandle ReadSyncOverAsync(int timeoutRemaining, out uint error);
internal abstract PacketHandle ReadAsync(SessionHandle handle, out uint error);
internal abstract uint CheckConnection();
internal abstract uint SetConnectionBufferSize(ref uint unsignedPacketSize);
internal abstract void ReleasePacket(PacketHandle syncReadPacket);
protected abstract uint SNIPacketGetData(PacketHandle packet, byte[] _inBuff, ref uint dataSize);
internal abstract PacketHandle GetResetWritePacket(int dataSize);
internal abstract void ClearAllWritePackets();
internal abstract PacketHandle AddPacketToPendingList(PacketHandle packet);
protected abstract void RemovePacketFromPendingList(PacketHandle pointer);
internal abstract uint GenerateSspiClientContext(byte[] receivedBuff, uint receivedLength, ref byte[] sendBuff, ref uint sendLength, byte[][] _sniSpnBuffer);
internal int DecrementPendingCallbacks(bool release)
{
int remaining = Interlocked.Decrement(ref _pendingCallbacks);
SqlClientEventSource.Log.TryAdvancedTraceEvent("TdsParserStateObject.DecrementPendingCallbacks | ADV | State Object Id {0}, after decrementing _pendingCallbacks: {1}", _objectID, _pendingCallbacks);
FreeGcHandle(remaining, release);
// NOTE: TdsParserSessionPool may call DecrementPendingCallbacks on a TdsParserStateObject which is already disposed
// This is not dangerous (since the stateObj is no longer in use), but we need to add a workaround in the assert for it
Debug.Assert((remaining == -1 && SessionHandle.IsNull) || (0 <= remaining && remaining < 3), $"_pendingCallbacks values is invalid after decrementing: {remaining}");
return remaining;
}
internal int IncrementPendingCallbacks()
{
int remaining = Interlocked.Increment(ref _pendingCallbacks);
SqlClientEventSource.Log.TryAdvancedTraceEvent("TdsParserStateObject.IncrementPendingCallbacks | ADV | State Object Id {0}, after incrementing _pendingCallbacks: {1}", _objectID, _pendingCallbacks);
Debug.Assert(0 < remaining && remaining <= 3, $"_pendingCallbacks values is invalid after incrementing: {remaining}");
return remaining;
}
internal void StartSession(object cancellationOwner)
{
_cancellationOwner.Target = cancellationOwner;
}
///////////////////////////////////////
// Buffer read methods - data values //
///////////////////////////////////////
// look at the next byte without pulling it off the wire, don't just return _inBytesUsed since we may
// have to go to the network to get the next byte.
internal bool TryPeekByte(out byte value)
{
if (!TryReadByte(out value))
{
return false;
}
// now do fixup
_inBytesPacket++;
_inBytesUsed--;
AssertValidState();
return true;
}
// Takes a byte array, an offset, and a len and fills the array from the offset to len number of
// bytes from the in buffer.
public bool TryReadByteArray(Span<byte> buff, int len)
{
return TryReadByteArray(buff, len, out _);
}
// NOTE: This method must be retriable WITHOUT replaying a snapshot
// Every time you call this method increment the offset and decrease len by the value of totalRead
public bool TryReadByteArray(Span<byte> buff, int len, out int totalRead)
{
#if NETFRAMEWORK
TdsParser.ReliabilitySection.Assert("unreliable call to ReadByteArray"); // you need to setup for a thread abort somewhere before you call this method
#endif
totalRead = 0;
#if DEBUG
if (_snapshot != null && _snapshot.DoPend())
{
_networkPacketTaskSource = new TaskCompletionSource<object>();
Interlocked.MemoryBarrier();
if (s_forcePendingReadsToWaitForUser)
{
_realNetworkPacketTaskSource = new TaskCompletionSource<object>();
_realNetworkPacketTaskSource.SetResult(null);
}
else
{
_networkPacketTaskSource.TrySetResult(null);
}
return false;
}
#endif
Debug.Assert(buff.IsEmpty || buff.Length >= len, "Invalid length sent to ReadByteArray()!");
// loop through and read up to array length
while (len > 0)
{
if ((_inBytesPacket == 0) || (_inBytesUsed == _inBytesRead))
{
if (!TryPrepareBuffer())
{
return false;
}
}
int bytesToRead = Math.Min(len, Math.Min(_inBytesPacket, _inBytesRead - _inBytesUsed));
Debug.Assert(bytesToRead > 0, "0 byte read in TryReadByteArray");
if (!buff.IsEmpty)
{
ReadOnlySpan<byte> copyFrom = new ReadOnlySpan<byte>(_inBuff, _inBytesUsed, bytesToRead);
Span<byte> copyTo = buff.Slice(totalRead, bytesToRead);
copyFrom.CopyTo(copyTo);
}
totalRead += bytesToRead;
_inBytesUsed += bytesToRead;
_inBytesPacket -= bytesToRead;
len -= bytesToRead;
AssertValidState();
}
return true;
}
// Takes no arguments and returns a byte from the buffer. If the buffer is empty, it is filled
// before the byte is returned.
internal bool TryReadByte(out byte value)
{
#if NETFRAMEWORK
TdsParser.ReliabilitySection.Assert("unreliable call to ReadByte"); // you need to setup for a thread abort somewhere before you call this method
#endif
Debug.Assert(_inBytesUsed >= 0 && _inBytesUsed <= _inBytesRead, "ERROR - TDSParser: _inBytesUsed < 0 or _inBytesUsed > _inBytesRead");
value = 0;
#if DEBUG
if (_snapshot != null && _snapshot.DoPend())
{
_networkPacketTaskSource = new TaskCompletionSource<object>();
Interlocked.MemoryBarrier();
if (s_forcePendingReadsToWaitForUser)
{
_realNetworkPacketTaskSource = new TaskCompletionSource<object>();
_realNetworkPacketTaskSource.SetResult(null);
}
else
{
_networkPacketTaskSource.TrySetResult(null);
}
return false;
}
#endif
if ((_inBytesPacket == 0) || (_inBytesUsed == _inBytesRead))
{
if (!TryPrepareBuffer())
{
return false;
}
}
// decrement the number of bytes left in the packet
_inBytesPacket--;
Debug.Assert(_inBytesPacket >= 0, "ERROR - TDSParser: _inBytesPacket < 0");
// return the byte from the buffer and increment the counter for number of bytes used in the in buffer
value = (_inBuff[_inBytesUsed++]);
AssertValidState();
return true;
}
internal bool TryReadChar(out char value)
{
Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
Span<byte> buffer = stackalloc byte[2];
if (((_inBytesUsed + 2) > _inBytesRead) || (_inBytesPacket < 2))
{
// If the char isn't fully in the buffer, or if it isn't fully in the packet,
// then use ReadByteArray since the logic is there to take care of that.
if (!TryReadByteArray(buffer, 2))
{
value = '\0';
return false;
}
}
else
{
// The entire char is in the packet and in the buffer, so just return it
// and take care of the counters.
buffer = _inBuff.AsSpan(_inBytesUsed, 2);
_inBytesUsed += 2;
_inBytesPacket -= 2;
}
AssertValidState();
value = (char)((buffer[1] << 8) + buffer[0]);
return true;
}
internal bool TryReadInt16(out short value)
{
Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
Span<byte> buffer = stackalloc byte[2];
if (((_inBytesUsed + 2) > _inBytesRead) || (_inBytesPacket < 2))
{
// If the int16 isn't fully in the buffer, or if it isn't fully in the packet,
// then use ReadByteArray since the logic is there to take care of that.
if (!TryReadByteArray(buffer, 2))
{
value = default;
return false;
}
}
else
{
// The entire int16 is in the packet and in the buffer, so just return it
// and take care of the counters.
buffer = _inBuff.AsSpan(_inBytesUsed, 2);
_inBytesUsed += 2;
_inBytesPacket -= 2;
}
AssertValidState();
value = (short)((buffer[1] << 8) + buffer[0]);
return true;
}
internal bool TryReadInt32(out int value)
{
Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
Span<byte> buffer = stackalloc byte[4];
if (((_inBytesUsed + 4) > _inBytesRead) || (_inBytesPacket < 4))
{
// If the int isn't fully in the buffer, or if it isn't fully in the packet,
// then use ReadByteArray since the logic is there to take care of that.
if (!TryReadByteArray(buffer, 4))
{
value = 0;
return false;
}
}
else
{
// The entire int is in the packet and in the buffer, so just return it
// and take care of the counters.
buffer = _inBuff.AsSpan(_inBytesUsed, 4);
_inBytesUsed += 4;
_inBytesPacket -= 4;
}
AssertValidState();
value = (buffer[3] << 24) + (buffer[2] << 16) + (buffer[1] << 8) + buffer[0];
return true;
}
// This method is safe to call when doing async without snapshot
internal bool TryReadInt64(out long value)
{
if ((_inBytesPacket == 0) || (_inBytesUsed == _inBytesRead))
{
if (!TryPrepareBuffer())
{
value = 0;
return false;
}
}
if ((_bTmpRead > 0) || (((_inBytesUsed + 8) > _inBytesRead) || (_inBytesPacket < 8)))
{
// If the long isn't fully in the buffer, or if it isn't fully in the packet,
// then use ReadByteArray since the logic is there to take care of that.
int bytesRead;
if (!TryReadByteArray(_bTmp.AsSpan(start: _bTmpRead), 8 - _bTmpRead, out bytesRead))
{
Debug.Assert(_bTmpRead + bytesRead <= 8, "Read more data than required");
_bTmpRead += bytesRead;
value = 0;
return false;
}
else
{
Debug.Assert(_bTmpRead + bytesRead == 8, "TryReadByteArray returned true without reading all data required");
_bTmpRead = 0;
AssertValidState();
value = BitConverter.ToInt64(_bTmp, 0);
return true;
}
}
else
{
// The entire long is in the packet and in the buffer, so just return it
// and take care of the counters.
value = BitConverter.ToInt64(_inBuff, _inBytesUsed);
_inBytesUsed += 8;
_inBytesPacket -= 8;
AssertValidState();
return true;
}
}
internal bool TryReadUInt16(out ushort value)
{
Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
Span<byte> buffer = stackalloc byte[2];
if (((_inBytesUsed + 2) > _inBytesRead) || (_inBytesPacket < 2))
{
// If the uint16 isn't fully in the buffer, or if it isn't fully in the packet,
// then use ReadByteArray since the logic is there to take care of that.
if (!TryReadByteArray(buffer, 2))
{
value = default;
return false;
}
}
else
{
// The entire uint16 is in the packet and in the buffer, so just return it
// and take care of the counters.
buffer = _inBuff.AsSpan(_inBytesUsed, 2);
_inBytesUsed += 2;
_inBytesPacket -= 2;
}
AssertValidState();
value = (ushort)((buffer[1] << 8) + buffer[0]);
return true;
}
// This method is safe to call when doing async without replay
internal bool TryReadUInt32(out uint value)
{
if ((_inBytesPacket == 0) || (_inBytesUsed == _inBytesRead))
{
if (!TryPrepareBuffer())
{
value = 0;
return false;
}
}
if ((_bTmpRead > 0) || (((_inBytesUsed + 4) > _inBytesRead) || (_inBytesPacket < 4)))
{
// If the int isn't fully in the buffer, or if it isn't fully in the packet,
// then use ReadByteArray since the logic is there to take care of that.
int bytesRead;
if (!TryReadByteArray(_bTmp.AsSpan(start: _bTmpRead), 4 - _bTmpRead, out bytesRead))
{
Debug.Assert(_bTmpRead + bytesRead <= 4, "Read more data than required");
_bTmpRead += bytesRead;
value = 0;
return false;
}
else
{
Debug.Assert(_bTmpRead + bytesRead == 4, "TryReadByteArray returned true without reading all data required");
_bTmpRead = 0;
AssertValidState();
value = BitConverter.ToUInt32(_bTmp, 0);
return true;
}
}
else
{
// The entire int is in the packet and in the buffer, so just return it
// and take care of the counters.
value = BitConverter.ToUInt32(_inBuff, _inBytesUsed);
_inBytesUsed += 4;
_inBytesPacket -= 4;
AssertValidState();
return true;
}
}
internal bool TryReadSingle(out float value)
{
Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
if (((_inBytesUsed + 4) > _inBytesRead) || (_inBytesPacket < 4))
{
// If the float isn't fully in the buffer, or if it isn't fully in the packet,
// then use ReadByteArray since the logic is there to take care of that.
if (!TryReadByteArray(_bTmp, 4))
{
value = default;
return false;
}
AssertValidState();
value = BitConverter.ToSingle(_bTmp, 0);
return true;
}
else
{
// The entire float is in the packet and in the buffer, so just return it
// and take care of the counters.
value = BitConverter.ToSingle(_inBuff, _inBytesUsed);
_inBytesUsed += 4;
_inBytesPacket -= 4;
AssertValidState();
return true;
}
}
internal bool TryReadDouble(out double value)
{
Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
if (((_inBytesUsed + 8) > _inBytesRead) || (_inBytesPacket < 8))
{
// If the double isn't fully in the buffer, or if it isn't fully in the packet,
// then use ReadByteArray since the logic is there to take care of that.
if (!TryReadByteArray(_bTmp, 8))
{
value = default;
return false;
}
AssertValidState();
value = BitConverter.ToDouble(_bTmp, 0);
return true;
}
else
{
// The entire double is in the packet and in the buffer, so just return it
// and take care of the counters.
value = BitConverter.ToDouble(_inBuff, _inBytesUsed);
_inBytesUsed += 8;
_inBytesPacket -= 8;
AssertValidState();
return true;
}
}
internal bool TryReadString(int length, out string value)
{
Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
int cBytes = length << 1;
byte[] buf;
int offset = 0;
if (((_inBytesUsed + cBytes) > _inBytesRead) || (_inBytesPacket < cBytes))
{
if (_bTmp == null || _bTmp.Length < cBytes)
{
_bTmp = new byte[cBytes];
}
if (!TryReadByteArray(_bTmp, cBytes))
{
value = null;
return false;
}
// assign local to point to parser scratch buffer
buf = _bTmp;
AssertValidState();
}
else
{
// assign local to point to _inBuff
buf = _inBuff;
offset = _inBytesUsed;
_inBytesUsed += cBytes;
_inBytesPacket -= cBytes;
AssertValidState();
}
value = System.Text.Encoding.Unicode.GetString(buf, offset, cBytes);
return true;
}
internal bool TryReadStringWithEncoding(int length, System.Text.Encoding encoding, bool isPlp, out string value)
{
Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
if (null == encoding)
{
// Need to skip the current column before throwing the error - this ensures that the state shared between this and the data reader is consistent when calling DrainData
if (isPlp)
{
if (!_parser.TrySkipPlpValue((ulong)length, this, out _))
{
value = null;
return false;
}
}
else
{
if (!TrySkipBytes(length))
{
value = null;
return false;
}
}
_parser.ThrowUnsupportedCollationEncountered(this);
}
byte[] buf = null;
int offset = 0;
if (isPlp)
{
if (!TryReadPlpBytes(ref buf, 0, int.MaxValue, out length))
{
value = null;
return false;
}
AssertValidState();
}
else
{
if (((_inBytesUsed + length) > _inBytesRead) || (_inBytesPacket < length))
{
if (_bTmp == null || _bTmp.Length < length)
{
_bTmp = new byte[length];
}
if (!TryReadByteArray(_bTmp, length))
{
value = null;
return false;
}
// assign local to point to parser scratch buffer
buf = _bTmp;
AssertValidState();
}
else
{
// assign local to point to _inBuff
buf = _inBuff;
offset = _inBytesUsed;
_inBytesUsed += length;
_inBytesPacket -= length;
AssertValidState();
}
}
// BCL optimizes to not use char[] underneath
value = encoding.GetString(buf, offset, length);
return true;
}
internal ulong ReadPlpLength(bool returnPlpNullIfNull)
{
ulong value;
Debug.Assert(_syncOverAsync, "Should not attempt pends in a synchronous call");
bool result = TryReadPlpLength(returnPlpNullIfNull, out value);
if (!result)
{
throw SQL.SynchronousCallMayNotPend();
}
return value;
}
// Reads the length of either the entire data or the length of the next chunk in a
// partially length prefixed data
// After this call, call ReadPlpBytes/ReadPlpUnicodeChars until the specified length of data
// is consumed. Repeat this until ReadPlpLength returns 0 in order to read the
// entire stream.
// When this function returns 0, it means the data stream is read completely and the
// plp state in the tdsparser is cleaned.
internal bool TryReadPlpLength(bool returnPlpNullIfNull, out ulong lengthLeft)
{
uint chunklen;
// bool firstchunk = false;
bool isNull = false;
Debug.Assert(_longlenleft == 0, "Out of synch length read request");
if (_longlen == 0)
{
// First chunk is being read. Find out what type of chunk it is
long value;
if (!TryReadInt64(out value))
{
lengthLeft = 0;
return false;
}
_longlen = (ulong)value;
// firstchunk = true;
}
if (_longlen == TdsEnums.SQL_PLP_NULL)
{
_longlen = 0;
_longlenleft = 0;
isNull = true;
}
else
{
// Data is coming in uint chunks, read length of next chunk
if (!TryReadUInt32(out chunklen))
{
lengthLeft = 0;
return false;
}
if (chunklen == TdsEnums.SQL_PLP_CHUNK_TERMINATOR)
{
_longlenleft = 0;
_longlen = 0;
}
else
{
_longlenleft = chunklen;
}
}
AssertValidState();
if (isNull && returnPlpNullIfNull)
{
lengthLeft = TdsEnums.SQL_PLP_NULL;
return true;
}
lengthLeft = _longlenleft;
return true;
}
internal int ReadPlpBytesChunk(byte[] buff, int offset, int len)
{
Debug.Assert(_syncOverAsync, "Should not attempt pends in a synchronous call");
Debug.Assert(_longlenleft > 0, "Read when no data available");
int value;
int bytesToRead = (int)Math.Min(_longlenleft, (ulong)len);
bool result = TryReadByteArray(buff.AsSpan(offset), bytesToRead, out value);
_longlenleft -= (ulong)bytesToRead;
if (!result)
{
throw SQL.SynchronousCallMayNotPend();
}
return value;
}
// Reads the requested number of bytes from a plp data stream, or the entire data if
// requested length is -1 or larger than the actual length of data. First call to this method
// should be preceeded by a call to ReadPlpLength or ReadDataLength.
// Returns the actual bytes read.
// NOTE: This method must be retriable WITHOUT replaying a snapshot
// Every time you call this method increment the offset and decrease len by the value of totalBytesRead
internal bool TryReadPlpBytes(ref byte[] buff, int offset, int len, out int totalBytesRead)
{
int bytesRead;
int bytesLeft;
byte[] newbuf;
if (_longlen == 0)
{
Debug.Assert(_longlenleft == 0);
if (buff == null)
{
buff = Array.Empty<byte>();
}
AssertValidState();
totalBytesRead = 0;
return true; // No data
}
Debug.Assert(_longlen != TdsEnums.SQL_PLP_NULL, "Out of sync plp read request");
Debug.Assert((buff == null && offset == 0) || (buff.Length >= offset + len), "Invalid length sent to ReadPlpBytes()!");
bytesLeft = len;
// If total length is known up front, allocate the whole buffer in one shot instead of realloc'ing and copying over each time
if (buff == null && _longlen != TdsEnums.SQL_PLP_UNKNOWNLEN)
{
if (_snapshot != null)
{
// if there is a snapshot and it contains a stored plp buffer take it
// and try to use it if it is the right length
buff = _snapshot._plpBuffer;
_snapshot._plpBuffer = null;
}
if ((ulong)(buff?.Length ?? 0) != _longlen)
{
// if the buffer is null or the wrong length create one to use
buff = new byte[(Math.Min((int)_longlen, len))];
}
}
if (_longlenleft == 0)
{
if (!TryReadPlpLength(false, out _))
{
totalBytesRead = 0;
return false;
}
if (_longlenleft == 0)
{ // Data read complete
totalBytesRead = 0;
return true;
}
}
if (buff == null)
{
buff = new byte[_longlenleft];
}
totalBytesRead = 0;
while (bytesLeft > 0)
{
int bytesToRead = (int)Math.Min(_longlenleft, (ulong)bytesLeft);
if (buff.Length < (offset + bytesToRead))
{
// Grow the array
newbuf = new byte[offset + bytesToRead];
Buffer.BlockCopy(buff, 0, newbuf, 0, offset);
buff = newbuf;
}
bool result = TryReadByteArray(buff.AsSpan(offset), bytesToRead, out bytesRead);
Debug.Assert(bytesRead <= bytesLeft, "Read more bytes than we needed");
Debug.Assert((ulong)bytesRead <= _longlenleft, "Read more bytes than is available");
bytesLeft -= bytesRead;
offset += bytesRead;
totalBytesRead += bytesRead;
_longlenleft -= (ulong)bytesRead;
if (!result)
{
if (_snapshot != null)
{
// a partial read has happened so store the target buffer in the snapshot
// so it can be re-used when another packet arrives and we read again