forked from dotnet/fsharp
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathilread.fs
More file actions
4148 lines (3660 loc) · 199 KB
/
Copy pathilread.fs
File metadata and controls
4148 lines (3660 loc) · 199 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) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
//---------------------------------------------------------------------
// The big binary reader
//
//---------------------------------------------------------------------
module FSharp.Compiler.AbstractIL.ILBinaryReader
#nowarn "42" // This construct is deprecated: it is only for use in the F# library
open System
open System.Collections.Concurrent
open System.Collections.Generic
open System.Diagnostics
open System.IO
open System.Runtime.InteropServices
open System.Text
open Internal.Utilities
open Internal.Utilities.Collections
open FSharp.Compiler.AbstractIL
open FSharp.Compiler.AbstractIL.Internal
#if !FX_NO_PDB_READER
open FSharp.Compiler.AbstractIL.Internal.Support
#endif
open FSharp.Compiler.AbstractIL.Diagnostics
open FSharp.Compiler.AbstractIL.Internal.BinaryConstants
open FSharp.Compiler.AbstractIL.IL
open FSharp.Compiler.AbstractIL.Internal.Library
open FSharp.Compiler.ErrorLogger
open FSharp.Compiler.Range
open Microsoft.FSharp.NativeInterop
open System.Reflection
let checking = false
let logging = false
let _ = if checking then dprintn "warning: ILBinaryReader.checking is on"
let noStableFileHeuristic = try (System.Environment.GetEnvironmentVariable("FSharp_NoStableFileHeuristic") <> null) with _ -> false
let alwaysMemoryMapFSC = try (System.Environment.GetEnvironmentVariable("FSharp_AlwaysMemoryMapCommandLineCompiler") <> null) with _ -> false
let stronglyHeldReaderCacheSizeDefault = 30
let stronglyHeldReaderCacheSize = try (match System.Environment.GetEnvironmentVariable("FSharp_StronglyHeldBinaryReaderCacheSize") with null -> stronglyHeldReaderCacheSizeDefault | s -> int32 s) with _ -> stronglyHeldReaderCacheSizeDefault
let singleOfBits (x: int32) = System.BitConverter.ToSingle(System.BitConverter.GetBytes x, 0)
let doubleOfBits (x: int64) = System.BitConverter.Int64BitsToDouble x
//---------------------------------------------------------------------
// Utilities.
//---------------------------------------------------------------------
let align alignment n = ((n + alignment - 0x1) / alignment) * alignment
let uncodedToken (tab: TableName) idx = ((tab.Index <<< 24) ||| idx)
let i32ToUncodedToken tok =
let idx = tok &&& 0xffffff
let tab = tok >>>& 24
(TableName.FromIndex tab, idx)
[<Struct>]
type TaggedIndex<'T> =
val tag: 'T
val index: int32
new(tag, index) = { tag=tag; index=index }
let uncodedTokenToTypeDefOrRefOrSpec (tab, tok) =
let tag =
if tab = TableNames.TypeDef then tdor_TypeDef
elif tab = TableNames.TypeRef then tdor_TypeRef
elif tab = TableNames.TypeSpec then tdor_TypeSpec
else failwith "bad table in uncodedTokenToTypeDefOrRefOrSpec"
TaggedIndex(tag, tok)
let uncodedTokenToMethodDefOrRef (tab, tok) =
let tag =
if tab = TableNames.Method then mdor_MethodDef
elif tab = TableNames.MemberRef then mdor_MemberRef
else failwith "bad table in uncodedTokenToMethodDefOrRef"
TaggedIndex(tag, tok)
let (|TaggedIndex|) (x: TaggedIndex<'T>) = x.tag, x.index
let tokToTaggedIdx f nbits tok =
let tagmask =
if nbits = 1 then 1
elif nbits = 2 then 3
elif nbits = 3 then 7
elif nbits = 4 then 15
elif nbits = 5 then 31
else failwith "too many nbits"
let tag = tok &&& tagmask
let idx = tok >>>& nbits
TaggedIndex(f tag, idx)
type Statistics =
{ mutable rawMemoryFileCount: int
mutable memoryMapFileOpenedCount: int
mutable memoryMapFileClosedCount: int
mutable weakByteFileCount: int
mutable byteFileCount: int }
let stats =
{ rawMemoryFileCount = 0
memoryMapFileOpenedCount = 0
memoryMapFileClosedCount = 0
weakByteFileCount = 0
byteFileCount = 0 }
let GetStatistics() = stats
[<AbstractClass>]
/// An abstraction over how we access the contents of .NET binaries. May be backed by managed or unmanaged memory,
/// memory mapped file or by on-disk resources. These objects should never need explicit disposal - they must either
/// not hold resources of clean up after themselves when collected.
type BinaryView() =
/// Read a byte from the file
abstract ReadByte: addr: int -> byte
/// Read a chunk of bytes from the file
abstract ReadBytes: addr: int -> int -> byte[]
/// Read an Int32 from the file
abstract ReadInt32: addr: int -> int
/// Read a UInt16 from the file
abstract ReadUInt16: addr: int -> uint16
/// Read a length of a UTF8 string from the file
abstract CountUtf8String: addr: int -> int
/// Read a UTF8 string from the file
abstract ReadUTF8String: addr: int -> string
/// An abstraction over how we access the contents of .NET binaries. May be backed by managed or unmanaged memory,
/// memory mapped file or by on-disk resources.
type BinaryFile =
/// Return a BinaryView for temporary use which eagerly holds any necessary memory resources for the duration of its lifetime,
/// and is faster to access byte-by-byte. The returned BinaryView should _not_ be captured in a closure that outlives the
/// desired lifetime.
abstract GetView: unit -> BinaryView
/// A view over a raw pointer to memory
type RawMemoryView(obj: obj, start: nativeint, len: int) =
inherit BinaryView()
override m.ReadByte i =
if nativeint i + 1n > nativeint len then failwithf "RawMemoryView overrun, i = %d, obj = %A" i obj
Marshal.ReadByte(start + nativeint i)
override m.ReadBytes i n =
if nativeint i + nativeint n > nativeint len then failwithf "RawMemoryView overrun, i = %d, n = %d, obj = %A" i n obj
let res = Bytes.zeroCreate n
Marshal.Copy(start + nativeint i, res, 0, n)
res
override m.ReadInt32 i =
if nativeint i + 4n > nativeint len then failwithf "RawMemoryView overrun, i = %d, obj = %A" i obj
Marshal.ReadInt32(start + nativeint i)
override m.ReadUInt16 i =
if nativeint i + 2n > nativeint len then failwithf "RawMemoryView overrun, i = %d, obj = %A" i obj
uint16(Marshal.ReadInt16(start + nativeint i))
override m.CountUtf8String i =
if nativeint i > nativeint len then failwithf "RawMemoryView overrun, i = %d, obj = %A" i obj
let pStart = start + nativeint i
let mutable p = start
while Marshal.ReadByte p <> 0uy do
p <- p + 1n
int (p - pStart)
override m.ReadUTF8String i =
let n = m.CountUtf8String i
if nativeint i + nativeint n > nativeint len then failwithf "RawMemoryView overrun, i = %d, n = %d, obj = %A" i n obj
System.Runtime.InteropServices.Marshal.PtrToStringAnsi(start + nativeint i, n)
member __.HoldObj() = obj
/// Gives views over a raw chunk of memory, for example those returned to us by the memory manager in Roslyn's
/// Visual Studio integration. 'obj' must keep the memory alive. The object will capture it and thus also keep the memory alive for
/// the lifetime of this object.
type RawMemoryFile(fileName: string, obj: obj, addr: nativeint, length: int) =
do stats.rawMemoryFileCount <- stats.rawMemoryFileCount + 1
let view = RawMemoryView(obj, addr, length)
member __.HoldObj() = obj // make sure we capture 'obj'
member __.FileName = fileName
interface BinaryFile with
override __.GetView() = view :>_
/// Read from memory mapped files.
module MemoryMapping =
type HANDLE = nativeint
type ADDR = nativeint
type SIZE_T = nativeint
[<DllImport("kernel32", SetLastError=true)>]
extern bool CloseHandle (HANDLE _handler)
[<DllImport("kernel32", SetLastError=true, CharSet=CharSet.Unicode)>]
extern HANDLE CreateFile (string _lpFileName,
int _dwDesiredAccess,
int _dwShareMode,
HANDLE _lpSecurityAttributes,
int _dwCreationDisposition,
int _dwFlagsAndAttributes,
HANDLE _hTemplateFile)
[<DllImport("kernel32", SetLastError=true, CharSet=CharSet.Unicode)>]
extern HANDLE CreateFileMapping (HANDLE _hFile,
HANDLE _lpAttributes,
int _flProtect,
int _dwMaximumSizeLow,
int _dwMaximumSizeHigh,
string _lpName)
[<DllImport("kernel32", SetLastError=true)>]
extern ADDR MapViewOfFile (HANDLE _hFileMappingObject,
int _dwDesiredAccess,
int _dwFileOffsetHigh,
int _dwFileOffsetLow,
SIZE_T _dwNumBytesToMap)
[<DllImport("kernel32", SetLastError=true)>]
extern bool UnmapViewOfFile (ADDR _lpBaseAddress)
let INVALID_HANDLE = new IntPtr(-1)
let MAP_READ = 0x0004
let GENERIC_READ = 0x80000000
let NULL_HANDLE = IntPtr.Zero
let FILE_SHARE_NONE = 0x0000
let FILE_SHARE_READ = 0x0001
let FILE_SHARE_WRITE = 0x0002
let FILE_SHARE_READ_WRITE = 0x0003
let CREATE_ALWAYS = 0x0002
let OPEN_EXISTING = 0x0003
let OPEN_ALWAYS = 0x0004
/// A view over a raw pointer to memory given by a memory mapped file.
/// NOTE: we should do more checking of validity here.
type MemoryMapView(start: nativeint) =
inherit BinaryView()
override m.ReadByte i =
Marshal.ReadByte(start + nativeint i)
override m.ReadBytes i n =
let res = Bytes.zeroCreate n
Marshal.Copy(start + nativeint i, res, 0, n)
res
override m.ReadInt32 i =
Marshal.ReadInt32(start + nativeint i)
override m.ReadUInt16 i =
uint16(Marshal.ReadInt16(start + nativeint i))
override m.CountUtf8String i =
let pStart = start + nativeint i
let mutable p = start
while Marshal.ReadByte p <> 0uy do
p <- p + 1n
int (p - pStart)
override m.ReadUTF8String i =
let n = m.CountUtf8String i
System.Runtime.InteropServices.Marshal.PtrToStringAnsi(start + nativeint i, n)
/// Memory maps a file and creates a single view over the entirety of its contents. The
/// lock on the file is only released when the object is disposed.
/// For memory mapping we currently take one view and never release it.
[<DebuggerDisplay("{FileName}")>]
type MemoryMapFile(fileName: string, view: MemoryMapView, hMap: MemoryMapping.HANDLE, hView: nativeint) =
do stats.memoryMapFileOpenedCount <- stats.memoryMapFileOpenedCount + 1
let mutable closed = false
static member Create fileName =
let hFile = MemoryMapping.CreateFile (fileName, MemoryMapping.GENERIC_READ, MemoryMapping.FILE_SHARE_READ_WRITE, IntPtr.Zero, MemoryMapping.OPEN_EXISTING, 0, IntPtr.Zero )
if hFile.Equals MemoryMapping.INVALID_HANDLE then
failwithf "CreateFile(0x%08x)" (Marshal.GetHRForLastWin32Error())
let protection = 0x00000002
let hMap = MemoryMapping.CreateFileMapping (hFile, IntPtr.Zero, protection, 0, 0, null )
ignore(MemoryMapping.CloseHandle hFile)
if hMap.Equals MemoryMapping.NULL_HANDLE then
failwithf "CreateFileMapping(0x%08x)" (Marshal.GetHRForLastWin32Error())
let hView = MemoryMapping.MapViewOfFile (hMap, MemoryMapping.MAP_READ, 0, 0, 0n)
if hView.Equals IntPtr.Zero then
failwithf "MapViewOfFile(0x%08x)" (Marshal.GetHRForLastWin32Error())
let view = MemoryMapView hView
MemoryMapFile(fileName, view, hMap, hView)
member __.FileName = fileName
member __.Close() =
stats.memoryMapFileClosedCount <- stats.memoryMapFileClosedCount + 1
if not closed then
closed <- true
MemoryMapping.UnmapViewOfFile hView |> ignore
MemoryMapping.CloseHandle hMap |> ignore
interface BinaryFile with
override __.GetView() = (view :> BinaryView)
/// Read file from memory blocks
type ByteView(bytes: byte[]) =
inherit BinaryView()
override __.ReadByte addr = bytes.[addr]
override __.ReadBytes addr len = Array.sub bytes addr len
override __.CountUtf8String addr =
let mutable p = addr
while bytes.[p] <> 0uy do
p <- p + 1
p - addr
override bfv.ReadUTF8String addr =
let n = bfv.CountUtf8String addr
System.Text.Encoding.UTF8.GetString (bytes, addr, n)
override bfv.ReadInt32 addr =
let b0 = bfv.ReadByte addr
let b1 = bfv.ReadByte (addr+1)
let b2 = bfv.ReadByte (addr+2)
let b3 = bfv.ReadByte (addr+3)
int b0 ||| (int b1 <<< 8) ||| (int b2 <<< 16) ||| (int b3 <<< 24)
override bfv.ReadUInt16 addr =
let b0 = bfv.ReadByte addr
let b1 = bfv.ReadByte (addr+1)
uint16 b0 ||| (uint16 b1 <<< 8)
/// A BinaryFile backed by an array of bytes held strongly as managed memory
[<DebuggerDisplay("{FileName}")>]
type ByteFile(fileName: string, bytes: byte[]) =
let view = ByteView bytes
do stats.byteFileCount <- stats.byteFileCount + 1
member __.FileName = fileName
interface BinaryFile with
override bf.GetView() = view :> BinaryView
/// Same as ByteFile but holds the bytes weakly. The bytes will be re-read from the backing file when a view is requested.
/// This is the default implementation used by F# Compiler Services when accessing "stable" binaries. It is not used
/// by Visual Studio, where tryGetMetadataSnapshot provides a RawMemoryFile backed by Roslyn data.
[<DebuggerDisplay("{FileName}")>]
type WeakByteFile(fileName: string, chunk: (int * int) option) =
do stats.weakByteFileCount <- stats.weakByteFileCount + 1
/// Used to check that the file hasn't changed
let fileStamp = FileSystem.GetLastWriteTimeShim fileName
/// The weak handle to the bytes for the file
let weakBytes = new WeakReference<byte[]> (null)
member __.FileName = fileName
/// Get the bytes for the file
interface BinaryFile with
override this.GetView() =
let strongBytes =
let mutable tg = null
if not (weakBytes.TryGetTarget(&tg)) then
if FileSystem.GetLastWriteTimeShim fileName <> fileStamp then
error (Error (FSComp.SR.ilreadFileChanged fileName, range0))
let bytes =
match chunk with
| None -> FileSystem.ReadAllBytesShim fileName
| Some(start, length) -> File.ReadBinaryChunk (fileName, start, length)
tg <- bytes
weakBytes.SetTarget bytes
tg
(ByteView strongBytes :> BinaryView)
let seekReadByte (mdv: BinaryView) addr = mdv.ReadByte addr
let seekReadBytes (mdv: BinaryView) addr len = mdv.ReadBytes addr len
let seekReadInt32 (mdv: BinaryView) addr = mdv.ReadInt32 addr
let seekReadUInt16 (mdv: BinaryView) addr = mdv.ReadUInt16 addr
let seekReadByteAsInt32 mdv addr = int32 (seekReadByte mdv addr)
let seekReadInt64 mdv addr =
let b0 = seekReadByte mdv addr
let b1 = seekReadByte mdv (addr+1)
let b2 = seekReadByte mdv (addr+2)
let b3 = seekReadByte mdv (addr+3)
let b4 = seekReadByte mdv (addr+4)
let b5 = seekReadByte mdv (addr+5)
let b6 = seekReadByte mdv (addr+6)
let b7 = seekReadByte mdv (addr+7)
int64 b0 ||| (int64 b1 <<< 8) ||| (int64 b2 <<< 16) ||| (int64 b3 <<< 24) |||
(int64 b4 <<< 32) ||| (int64 b5 <<< 40) ||| (int64 b6 <<< 48) ||| (int64 b7 <<< 56)
let seekReadUInt16AsInt32 mdv addr = int32 (seekReadUInt16 mdv addr)
let seekReadCompressedUInt32 mdv addr =
let b0 = seekReadByte mdv addr
if b0 <= 0x7Fuy then int b0, addr+1
elif b0 <= 0xBFuy then
let b0 = b0 &&& 0x7Fuy
let b1 = seekReadByteAsInt32 mdv (addr+1)
(int b0 <<< 8) ||| int b1, addr+2
else
let b0 = b0 &&& 0x3Fuy
let b1 = seekReadByteAsInt32 mdv (addr+1)
let b2 = seekReadByteAsInt32 mdv (addr+2)
let b3 = seekReadByteAsInt32 mdv (addr+3)
(int b0 <<< 24) ||| (int b1 <<< 16) ||| (int b2 <<< 8) ||| int b3, addr+4
let seekReadSByte mdv addr = sbyte (seekReadByte mdv addr)
let seekReadSingle mdv addr = singleOfBits (seekReadInt32 mdv addr)
let seekReadDouble mdv addr = doubleOfBits (seekReadInt64 mdv addr)
let rec seekCountUtf8String mdv addr n =
let c = seekReadByteAsInt32 mdv addr
if c = 0 then n
else seekCountUtf8String mdv (addr+1) (n+1)
let seekReadUTF8String mdv addr =
let n = seekCountUtf8String mdv addr 0
let bytes = seekReadBytes mdv addr n
System.Text.Encoding.UTF8.GetString (bytes, 0, bytes.Length)
let seekReadBlob mdv addr =
let len, addr = seekReadCompressedUInt32 mdv addr
seekReadBytes mdv addr len
let seekReadUserString mdv addr =
let len, addr = seekReadCompressedUInt32 mdv addr
let bytes = seekReadBytes mdv addr (len - 1)
Encoding.Unicode.GetString(bytes, 0, bytes.Length)
let seekReadGuid mdv addr = seekReadBytes mdv addr 0x10
let seekReadUncodedToken mdv addr =
i32ToUncodedToken (seekReadInt32 mdv addr)
//---------------------------------------------------------------------
// Primitives to help read signatures. These do not use the file cursor
//---------------------------------------------------------------------
let sigptrCheck (bytes: byte[]) sigptr =
if checking && sigptr >= bytes.Length then failwith "read past end of sig. "
// All this code should be moved to use a mutable index into the signature
//
//type SigPtr(bytes: byte[], sigptr: int) =
// let mutable curr = sigptr
// member x.GetByte() = let res = bytes.[curr] in curr <- curr + 1; res
let sigptrGetByte (bytes: byte[]) sigptr =
sigptrCheck bytes sigptr
bytes.[sigptr], sigptr + 1
let sigptrGetBool bytes sigptr =
let b0, sigptr = sigptrGetByte bytes sigptr
(b0 = 0x01uy), sigptr
let sigptrGetSByte bytes sigptr =
let i, sigptr = sigptrGetByte bytes sigptr
sbyte i, sigptr
let sigptrGetUInt16 bytes sigptr =
let b0, sigptr = sigptrGetByte bytes sigptr
let b1, sigptr = sigptrGetByte bytes sigptr
uint16 (int b0 ||| (int b1 <<< 8)), sigptr
let sigptrGetInt16 bytes sigptr =
let u, sigptr = sigptrGetUInt16 bytes sigptr
int16 u, sigptr
let sigptrGetInt32 bytes sigptr =
sigptrCheck bytes sigptr
let b0 = bytes.[sigptr]
let b1 = bytes.[sigptr+1]
let b2 = bytes.[sigptr+2]
let b3 = bytes.[sigptr+3]
let res = int b0 ||| (int b1 <<< 8) ||| (int b2 <<< 16) ||| (int b3 <<< 24)
res, sigptr + 4
let sigptrGetUInt32 bytes sigptr =
let u, sigptr = sigptrGetInt32 bytes sigptr
uint32 u, sigptr
let sigptrGetUInt64 bytes sigptr =
let u0, sigptr = sigptrGetUInt32 bytes sigptr
let u1, sigptr = sigptrGetUInt32 bytes sigptr
(uint64 u0 ||| (uint64 u1 <<< 32)), sigptr
let sigptrGetInt64 bytes sigptr =
let u, sigptr = sigptrGetUInt64 bytes sigptr
int64 u, sigptr
let sigptrGetSingle bytes sigptr =
let u, sigptr = sigptrGetInt32 bytes sigptr
singleOfBits u, sigptr
let sigptrGetDouble bytes sigptr =
let u, sigptr = sigptrGetInt64 bytes sigptr
doubleOfBits u, sigptr
let sigptrGetZInt32 bytes sigptr =
let b0, sigptr = sigptrGetByte bytes sigptr
if b0 <= 0x7Fuy then int b0, sigptr
elif b0 <= 0xBFuy then
let b0 = b0 &&& 0x7Fuy
let b1, sigptr = sigptrGetByte bytes sigptr
(int b0 <<< 8) ||| int b1, sigptr
else
let b0 = b0 &&& 0x3Fuy
let b1, sigptr = sigptrGetByte bytes sigptr
let b2, sigptr = sigptrGetByte bytes sigptr
let b3, sigptr = sigptrGetByte bytes sigptr
(int b0 <<< 24) ||| (int b1 <<< 16) ||| (int b2 <<< 8) ||| int b3, sigptr
let rec sigptrFoldAcc f n (bytes: byte[]) (sigptr: int) i acc =
if i < n then
let x, sp = f bytes sigptr
sigptrFoldAcc f n bytes sp (i+1) (x :: acc)
else
List.rev acc, sigptr
let sigptrFold f n (bytes: byte[]) (sigptr: int) =
sigptrFoldAcc f n bytes sigptr 0 []
let sigptrGetBytes n (bytes: byte[]) sigptr =
if checking && sigptr + n >= bytes.Length then
dprintn "read past end of sig. in sigptrGetString"
Bytes.zeroCreate 0, sigptr
else
let res = Bytes.zeroCreate n
for i = 0 to (n - 1) do
res.[i] <- bytes.[sigptr + i]
res, sigptr + n
let sigptrGetString n bytes sigptr =
let bytearray, sigptr = sigptrGetBytes n bytes sigptr
(System.Text.Encoding.UTF8.GetString(bytearray, 0, bytearray.Length)), sigptr
// --------------------------------------------------------------------
// Now the tables of instructions
// --------------------------------------------------------------------
[<NoEquality; NoComparison>]
type ILInstrPrefixesRegister =
{ mutable al: ILAlignment
mutable tl: ILTailcall
mutable vol: ILVolatility
mutable ro: ILReadonly
mutable constrained: ILType option}
let noPrefixes mk prefixes =
if prefixes.al <> Aligned then failwith "an unaligned prefix is not allowed here"
if prefixes.vol <> Nonvolatile then failwith "a volatile prefix is not allowed here"
if prefixes.tl <> Normalcall then failwith "a tailcall prefix is not allowed here"
if prefixes.ro <> NormalAddress then failwith "a readonly prefix is not allowed here"
if prefixes.constrained <> None then failwith "a constrained prefix is not allowed here"
mk
let volatileOrUnalignedPrefix mk prefixes =
if prefixes.tl <> Normalcall then failwith "a tailcall prefix is not allowed here"
if prefixes.constrained <> None then failwith "a constrained prefix is not allowed here"
if prefixes.ro <> NormalAddress then failwith "a readonly prefix is not allowed here"
mk (prefixes.al, prefixes.vol)
let volatilePrefix mk prefixes =
if prefixes.al <> Aligned then failwith "an unaligned prefix is not allowed here"
if prefixes.tl <> Normalcall then failwith "a tailcall prefix is not allowed here"
if prefixes.constrained <> None then failwith "a constrained prefix is not allowed here"
if prefixes.ro <> NormalAddress then failwith "a readonly prefix is not allowed here"
mk prefixes.vol
let tailPrefix mk prefixes =
if prefixes.al <> Aligned then failwith "an unaligned prefix is not allowed here"
if prefixes.vol <> Nonvolatile then failwith "a volatile prefix is not allowed here"
if prefixes.constrained <> None then failwith "a constrained prefix is not allowed here"
if prefixes.ro <> NormalAddress then failwith "a readonly prefix is not allowed here"
mk prefixes.tl
let constraintOrTailPrefix mk prefixes =
if prefixes.al <> Aligned then failwith "an unaligned prefix is not allowed here"
if prefixes.vol <> Nonvolatile then failwith "a volatile prefix is not allowed here"
if prefixes.ro <> NormalAddress then failwith "a readonly prefix is not allowed here"
mk (prefixes.constrained, prefixes.tl )
let readonlyPrefix mk prefixes =
if prefixes.al <> Aligned then failwith "an unaligned prefix is not allowed here"
if prefixes.vol <> Nonvolatile then failwith "a volatile prefix is not allowed here"
if prefixes.tl <> Normalcall then failwith "a tailcall prefix is not allowed here"
if prefixes.constrained <> None then failwith "a constrained prefix is not allowed here"
mk prefixes.ro
[<NoEquality; NoComparison>]
type ILInstrDecoder =
| I_u16_u8_instr of (ILInstrPrefixesRegister -> uint16 -> ILInstr)
| I_u16_u16_instr of (ILInstrPrefixesRegister -> uint16 -> ILInstr)
| I_none_instr of (ILInstrPrefixesRegister -> ILInstr)
| I_i64_instr of (ILInstrPrefixesRegister -> int64 -> ILInstr)
| I_i32_i32_instr of (ILInstrPrefixesRegister -> int32 -> ILInstr)
| I_i32_i8_instr of (ILInstrPrefixesRegister -> int32 -> ILInstr)
| I_r4_instr of (ILInstrPrefixesRegister -> single -> ILInstr)
| I_r8_instr of (ILInstrPrefixesRegister -> double -> ILInstr)
| I_field_instr of (ILInstrPrefixesRegister -> ILFieldSpec -> ILInstr)
| I_method_instr of (ILInstrPrefixesRegister -> ILMethodSpec * ILVarArgs -> ILInstr)
| I_unconditional_i32_instr of (ILInstrPrefixesRegister -> ILCodeLabel -> ILInstr)
| I_unconditional_i8_instr of (ILInstrPrefixesRegister -> ILCodeLabel -> ILInstr)
| I_conditional_i32_instr of (ILInstrPrefixesRegister -> ILCodeLabel -> ILInstr)
| I_conditional_i8_instr of (ILInstrPrefixesRegister -> ILCodeLabel -> ILInstr)
| I_string_instr of (ILInstrPrefixesRegister -> string -> ILInstr)
| I_switch_instr of (ILInstrPrefixesRegister -> ILCodeLabel list -> ILInstr)
| I_tok_instr of (ILInstrPrefixesRegister -> ILToken -> ILInstr)
| I_sig_instr of (ILInstrPrefixesRegister -> ILCallingSignature * ILVarArgs -> ILInstr)
| I_type_instr of (ILInstrPrefixesRegister -> ILType -> ILInstr)
| I_invalid_instr
let mkStind dt = volatileOrUnalignedPrefix (fun (x, y) -> I_stind(x, y, dt))
let mkLdind dt = volatileOrUnalignedPrefix (fun (x, y) -> I_ldind(x, y, dt))
let instrs () =
[ i_ldarg_s, I_u16_u8_instr (noPrefixes mkLdarg)
i_starg_s, I_u16_u8_instr (noPrefixes I_starg)
i_ldarga_s, I_u16_u8_instr (noPrefixes I_ldarga)
i_stloc_s, I_u16_u8_instr (noPrefixes mkStloc)
i_ldloc_s, I_u16_u8_instr (noPrefixes mkLdloc)
i_ldloca_s, I_u16_u8_instr (noPrefixes I_ldloca)
i_ldarg, I_u16_u16_instr (noPrefixes mkLdarg)
i_starg, I_u16_u16_instr (noPrefixes I_starg)
i_ldarga, I_u16_u16_instr (noPrefixes I_ldarga)
i_stloc, I_u16_u16_instr (noPrefixes mkStloc)
i_ldloc, I_u16_u16_instr (noPrefixes mkLdloc)
i_ldloca, I_u16_u16_instr (noPrefixes I_ldloca)
i_stind_i, I_none_instr (mkStind DT_I)
i_stind_i1, I_none_instr (mkStind DT_I1)
i_stind_i2, I_none_instr (mkStind DT_I2)
i_stind_i4, I_none_instr (mkStind DT_I4)
i_stind_i8, I_none_instr (mkStind DT_I8)
i_stind_r4, I_none_instr (mkStind DT_R4)
i_stind_r8, I_none_instr (mkStind DT_R8)
i_stind_ref, I_none_instr (mkStind DT_REF)
i_ldind_i, I_none_instr (mkLdind DT_I)
i_ldind_i1, I_none_instr (mkLdind DT_I1)
i_ldind_i2, I_none_instr (mkLdind DT_I2)
i_ldind_i4, I_none_instr (mkLdind DT_I4)
i_ldind_i8, I_none_instr (mkLdind DT_I8)
i_ldind_u1, I_none_instr (mkLdind DT_U1)
i_ldind_u2, I_none_instr (mkLdind DT_U2)
i_ldind_u4, I_none_instr (mkLdind DT_U4)
i_ldind_r4, I_none_instr (mkLdind DT_R4)
i_ldind_r8, I_none_instr (mkLdind DT_R8)
i_ldind_ref, I_none_instr (mkLdind DT_REF)
i_cpblk, I_none_instr (volatileOrUnalignedPrefix I_cpblk)
i_initblk, I_none_instr (volatileOrUnalignedPrefix I_initblk)
i_ldc_i8, I_i64_instr (noPrefixes (fun x ->(AI_ldc (DT_I8, ILConst.I8 x))))
i_ldc_i4, I_i32_i32_instr (noPrefixes mkLdcInt32)
i_ldc_i4_s, I_i32_i8_instr (noPrefixes mkLdcInt32)
i_ldc_r4, I_r4_instr (noPrefixes (fun x -> (AI_ldc (DT_R4, ILConst.R4 x))))
i_ldc_r8, I_r8_instr (noPrefixes (fun x -> (AI_ldc (DT_R8, ILConst.R8 x))))
i_ldfld, I_field_instr (volatileOrUnalignedPrefix(fun (x, y) fspec -> I_ldfld (x, y, fspec)))
i_stfld, I_field_instr (volatileOrUnalignedPrefix(fun (x, y) fspec -> I_stfld (x, y, fspec)))
i_ldsfld, I_field_instr (volatilePrefix (fun x fspec -> I_ldsfld (x, fspec)))
i_stsfld, I_field_instr (volatilePrefix (fun x fspec -> I_stsfld (x, fspec)))
i_ldflda, I_field_instr (noPrefixes I_ldflda)
i_ldsflda, I_field_instr (noPrefixes I_ldsflda)
i_call, I_method_instr (tailPrefix (fun tl (mspec, y) -> I_call (tl, mspec, y)))
i_ldftn, I_method_instr (noPrefixes (fun (mspec, _y) -> I_ldftn mspec))
i_ldvirtftn, I_method_instr (noPrefixes (fun (mspec, _y) -> I_ldvirtftn mspec))
i_newobj, I_method_instr (noPrefixes I_newobj)
i_callvirt, I_method_instr (constraintOrTailPrefix (fun (c, tl) (mspec, y) -> match c with Some ty -> I_callconstraint(tl, ty, mspec, y) | None -> I_callvirt (tl, mspec, y)))
i_leave_s, I_unconditional_i8_instr (noPrefixes (fun x -> I_leave x))
i_br_s, I_unconditional_i8_instr (noPrefixes I_br)
i_leave, I_unconditional_i32_instr (noPrefixes (fun x -> I_leave x))
i_br, I_unconditional_i32_instr (noPrefixes I_br)
i_brtrue_s, I_conditional_i8_instr (noPrefixes (fun x -> I_brcmp (BI_brtrue, x)))
i_brfalse_s, I_conditional_i8_instr (noPrefixes (fun x -> I_brcmp (BI_brfalse, x)))
i_beq_s, I_conditional_i8_instr (noPrefixes (fun x -> I_brcmp (BI_beq, x)))
i_blt_s, I_conditional_i8_instr (noPrefixes (fun x -> I_brcmp (BI_blt, x)))
i_blt_un_s, I_conditional_i8_instr (noPrefixes (fun x -> I_brcmp (BI_blt_un, x)))
i_ble_s, I_conditional_i8_instr (noPrefixes (fun x -> I_brcmp (BI_ble, x)))
i_ble_un_s, I_conditional_i8_instr (noPrefixes (fun x -> I_brcmp (BI_ble_un, x)))
i_bgt_s, I_conditional_i8_instr (noPrefixes (fun x -> I_brcmp (BI_bgt, x)))
i_bgt_un_s, I_conditional_i8_instr (noPrefixes (fun x -> I_brcmp (BI_bgt_un, x)))
i_bge_s, I_conditional_i8_instr (noPrefixes (fun x -> I_brcmp (BI_bge, x)))
i_bge_un_s, I_conditional_i8_instr (noPrefixes (fun x -> I_brcmp (BI_bge_un, x)))
i_bne_un_s, I_conditional_i8_instr (noPrefixes (fun x -> I_brcmp (BI_bne_un, x)))
i_brtrue, I_conditional_i32_instr (noPrefixes (fun x -> I_brcmp (BI_brtrue, x)))
i_brfalse, I_conditional_i32_instr (noPrefixes (fun x -> I_brcmp (BI_brfalse, x)))
i_beq, I_conditional_i32_instr (noPrefixes (fun x -> I_brcmp (BI_beq, x)))
i_blt, I_conditional_i32_instr (noPrefixes (fun x -> I_brcmp (BI_blt, x)))
i_blt_un, I_conditional_i32_instr (noPrefixes (fun x -> I_brcmp (BI_blt_un, x)))
i_ble, I_conditional_i32_instr (noPrefixes (fun x -> I_brcmp (BI_ble, x)))
i_ble_un, I_conditional_i32_instr (noPrefixes (fun x -> I_brcmp (BI_ble_un, x)))
i_bgt, I_conditional_i32_instr (noPrefixes (fun x -> I_brcmp (BI_bgt, x)))
i_bgt_un, I_conditional_i32_instr (noPrefixes (fun x -> I_brcmp (BI_bgt_un, x)))
i_bge, I_conditional_i32_instr (noPrefixes (fun x -> I_brcmp (BI_bge, x)))
i_bge_un, I_conditional_i32_instr (noPrefixes (fun x -> I_brcmp (BI_bge_un, x)))
i_bne_un, I_conditional_i32_instr (noPrefixes (fun x -> I_brcmp (BI_bne_un, x)))
i_ldstr, I_string_instr (noPrefixes I_ldstr)
i_switch, I_switch_instr (noPrefixes I_switch)
i_ldtoken, I_tok_instr (noPrefixes I_ldtoken)
i_calli, I_sig_instr (tailPrefix (fun tl (x, y) -> I_calli (tl, x, y)))
i_mkrefany, I_type_instr (noPrefixes I_mkrefany)
i_refanyval, I_type_instr (noPrefixes I_refanyval)
i_ldelema, I_type_instr (readonlyPrefix (fun ro x -> I_ldelema (ro, false, ILArrayShape.SingleDimensional, x)))
i_ldelem_any, I_type_instr (noPrefixes (fun x -> I_ldelem_any (ILArrayShape.SingleDimensional, x)))
i_stelem_any, I_type_instr (noPrefixes (fun x -> I_stelem_any (ILArrayShape.SingleDimensional, x)))
i_newarr, I_type_instr (noPrefixes (fun x -> I_newarr (ILArrayShape.SingleDimensional, x)))
i_castclass, I_type_instr (noPrefixes I_castclass)
i_isinst, I_type_instr (noPrefixes I_isinst)
i_unbox_any, I_type_instr (noPrefixes I_unbox_any)
i_cpobj, I_type_instr (noPrefixes I_cpobj)
i_initobj, I_type_instr (noPrefixes I_initobj)
i_ldobj, I_type_instr (volatileOrUnalignedPrefix (fun (x, y) z -> I_ldobj (x, y, z)))
i_stobj, I_type_instr (volatileOrUnalignedPrefix (fun (x, y) z -> I_stobj (x, y, z)))
i_sizeof, I_type_instr (noPrefixes I_sizeof)
i_box, I_type_instr (noPrefixes I_box)
i_unbox, I_type_instr (noPrefixes I_unbox) ]
// The tables are delayed to avoid building them unnecessarily at startup
// Many applications of AbsIL (e.g. a compiler) don't need to read instructions.
let oneByteInstrs = ref None
let twoByteInstrs = ref None
let fillInstrs () =
let oneByteInstrTable = Array.create 256 I_invalid_instr
let twoByteInstrTable = Array.create 256 I_invalid_instr
let addInstr (i, f) =
if i > 0xff then
assert (i >>>& 8 = 0xfe)
let i = (i &&& 0xff)
match twoByteInstrTable.[i] with
| I_invalid_instr -> ()
| _ -> dprintn ("warning: duplicate decode entries for "+string i)
twoByteInstrTable.[i] <- f
else
match oneByteInstrTable.[i] with
| I_invalid_instr -> ()
| _ -> dprintn ("warning: duplicate decode entries for "+string i)
oneByteInstrTable.[i] <- f
List.iter addInstr (instrs())
List.iter (fun (x, mk) -> addInstr (x, I_none_instr (noPrefixes mk))) (noArgInstrs.Force())
oneByteInstrs := Some oneByteInstrTable
twoByteInstrs := Some twoByteInstrTable
let rec getOneByteInstr i =
match !oneByteInstrs with
| None -> fillInstrs(); getOneByteInstr i
| Some t -> t.[i]
let rec getTwoByteInstr i =
match !twoByteInstrs with
| None -> fillInstrs(); getTwoByteInstr i
| Some t -> t.[i]
//---------------------------------------------------------------------
//
//---------------------------------------------------------------------
type ImageChunk = { size: int32; addr: int32 }
let chunk sz next = ({addr=next; size=sz}, next + sz)
let nochunk next = ({addr= 0x0;size= 0x0; }, next)
type RowElementKind =
| UShort
| ULong
| Byte
| Data
| GGuid
| Blob
| SString
| SimpleIndex of TableName
| TypeDefOrRefOrSpec
| TypeOrMethodDef
| HasConstant
| HasCustomAttribute
| HasFieldMarshal
| HasDeclSecurity
| MemberRefParent
| HasSemantics
| MethodDefOrRef
| MemberForwarded
| Implementation
| CustomAttributeType
| ResolutionScope
type RowKind = RowKind of RowElementKind list
let kindAssemblyRef = RowKind [ UShort; UShort; UShort; UShort; ULong; Blob; SString; SString; Blob; ]
let kindModuleRef = RowKind [ SString ]
let kindFileRef = RowKind [ ULong; SString; Blob ]
let kindTypeRef = RowKind [ ResolutionScope; SString; SString ]
let kindTypeSpec = RowKind [ Blob ]
let kindTypeDef = RowKind [ ULong; SString; SString; TypeDefOrRefOrSpec; SimpleIndex TableNames.Field; SimpleIndex TableNames.Method ]
let kindPropertyMap = RowKind [ SimpleIndex TableNames.TypeDef; SimpleIndex TableNames.Property ]
let kindEventMap = RowKind [ SimpleIndex TableNames.TypeDef; SimpleIndex TableNames.Event ]
let kindInterfaceImpl = RowKind [ SimpleIndex TableNames.TypeDef; TypeDefOrRefOrSpec ]
let kindNested = RowKind [ SimpleIndex TableNames.TypeDef; SimpleIndex TableNames.TypeDef ]
let kindCustomAttribute = RowKind [ HasCustomAttribute; CustomAttributeType; Blob ]
let kindDeclSecurity = RowKind [ UShort; HasDeclSecurity; Blob ]
let kindMemberRef = RowKind [ MemberRefParent; SString; Blob ]
let kindStandAloneSig = RowKind [ Blob ]
let kindFieldDef = RowKind [ UShort; SString; Blob ]
let kindFieldRVA = RowKind [ Data; SimpleIndex TableNames.Field ]
let kindFieldMarshal = RowKind [ HasFieldMarshal; Blob ]
let kindConstant = RowKind [ UShort;HasConstant; Blob ]
let kindFieldLayout = RowKind [ ULong; SimpleIndex TableNames.Field ]
let kindParam = RowKind [ UShort; UShort; SString ]
let kindMethodDef = RowKind [ ULong; UShort; UShort; SString; Blob; SimpleIndex TableNames.Param ]
let kindMethodImpl = RowKind [ SimpleIndex TableNames.TypeDef; MethodDefOrRef; MethodDefOrRef ]
let kindImplMap = RowKind [ UShort; MemberForwarded; SString; SimpleIndex TableNames.ModuleRef ]
let kindMethodSemantics = RowKind [ UShort; SimpleIndex TableNames.Method; HasSemantics ]
let kindProperty = RowKind [ UShort; SString; Blob ]
let kindEvent = RowKind [ UShort; SString; TypeDefOrRefOrSpec ]
let kindManifestResource = RowKind [ ULong; ULong; SString; Implementation ]
let kindClassLayout = RowKind [ UShort; ULong; SimpleIndex TableNames.TypeDef ]
let kindExportedType = RowKind [ ULong; ULong; SString; SString; Implementation ]
let kindAssembly = RowKind [ ULong; UShort; UShort; UShort; UShort; ULong; Blob; SString; SString ]
let kindGenericParam_v1_1 = RowKind [ UShort; UShort; TypeOrMethodDef; SString; TypeDefOrRefOrSpec ]
let kindGenericParam_v2_0 = RowKind [ UShort; UShort; TypeOrMethodDef; SString ]
let kindMethodSpec = RowKind [ MethodDefOrRef; Blob ]
let kindGenericParamConstraint = RowKind [ SimpleIndex TableNames.GenericParam; TypeDefOrRefOrSpec ]
let kindModule = RowKind [ UShort; SString; GGuid; GGuid; GGuid ]
let kindIllegal = RowKind [ ]
//---------------------------------------------------------------------
// Used for binary searches of sorted tables. Each function that reads
// a table row returns a tuple that contains the elements of the row.
// One of these elements may be a key for a sorted table. These
// keys can be compared using the functions below depending on the
// kind of element in that column.
//---------------------------------------------------------------------
let hcCompare (TaggedIndex((t1: HasConstantTag), (idx1: int))) (TaggedIndex((t2: HasConstantTag), idx2)) =
if idx1 < idx2 then -1 elif idx1 > idx2 then 1 else compare t1.Tag t2.Tag
let hsCompare (TaggedIndex((t1: HasSemanticsTag), (idx1: int))) (TaggedIndex((t2: HasSemanticsTag), idx2)) =
if idx1 < idx2 then -1 elif idx1 > idx2 then 1 else compare t1.Tag t2.Tag
let hcaCompare (TaggedIndex((t1: HasCustomAttributeTag), (idx1: int))) (TaggedIndex((t2: HasCustomAttributeTag), idx2)) =
if idx1 < idx2 then -1 elif idx1 > idx2 then 1 else compare t1.Tag t2.Tag
let mfCompare (TaggedIndex((t1: MemberForwardedTag), (idx1: int))) (TaggedIndex((t2: MemberForwardedTag), idx2)) =
if idx1 < idx2 then -1 elif idx1 > idx2 then 1 else compare t1.Tag t2.Tag
let hdsCompare (TaggedIndex((t1: HasDeclSecurityTag), (idx1: int))) (TaggedIndex((t2: HasDeclSecurityTag), idx2)) =
if idx1 < idx2 then -1 elif idx1 > idx2 then 1 else compare t1.Tag t2.Tag
let hfmCompare (TaggedIndex((t1: HasFieldMarshalTag), idx1)) (TaggedIndex((t2: HasFieldMarshalTag), idx2)) =
if idx1 < idx2 then -1 elif idx1 > idx2 then 1 else compare t1.Tag t2.Tag
let tomdCompare (TaggedIndex((t1: TypeOrMethodDefTag), idx1)) (TaggedIndex((t2: TypeOrMethodDefTag), idx2)) =
if idx1 < idx2 then -1 elif idx1 > idx2 then 1 else compare t1.Tag t2.Tag
let simpleIndexCompare (idx1: int) (idx2: int) =
compare idx1 idx2
//---------------------------------------------------------------------
// The various keys for the various caches.
//---------------------------------------------------------------------
type TypeDefAsTypIdx = TypeDefAsTypIdx of ILBoxity * ILGenericArgs * int
type TypeRefAsTypIdx = TypeRefAsTypIdx of ILBoxity * ILGenericArgs * int
type BlobAsMethodSigIdx = BlobAsMethodSigIdx of int * int32
type BlobAsFieldSigIdx = BlobAsFieldSigIdx of int * int32
type BlobAsPropSigIdx = BlobAsPropSigIdx of int * int32
type BlobAsLocalSigIdx = BlobAsLocalSigIdx of int * int32
type MemberRefAsMspecIdx = MemberRefAsMspecIdx of int * int
type MethodSpecAsMspecIdx = MethodSpecAsMspecIdx of int * int
type MemberRefAsFspecIdx = MemberRefAsFspecIdx of int * int
type CustomAttrIdx = CustomAttrIdx of CustomAttributeTypeTag * int * int32
type GenericParamsIdx = GenericParamsIdx of int * TypeOrMethodDefTag * int
//---------------------------------------------------------------------
// Polymorphic caches for row and heap readers
//---------------------------------------------------------------------
let mkCacheInt32 lowMem _inbase _nm _sz =
if lowMem then (fun f x -> f x) else
let cache = ref null
let count = ref 0
#if STATISTICS
addReport (fun oc -> if !count <> 0 then oc.WriteLine ((_inbase + string !count + " "+ _nm + " cache hits"): string))
#endif
fun f (idx: int32) ->
let cache =
match !cache with
| null -> cache := new Dictionary<int32, _>(11)
| _ -> ()
!cache
match cache.TryGetValue idx with
| true, res ->
incr count
res
| _ ->
let res = f idx
cache.[idx] <- res
res
let mkCacheGeneric lowMem _inbase _nm _sz =
if lowMem then (fun f x -> f x) else
let cache = ref null
let count = ref 0
#if STATISTICS
addReport (fun oc -> if !count <> 0 then oc.WriteLine ((_inbase + string !count + " " + _nm + " cache hits"): string))
#endif
fun f (idx :'T) ->
let cache =
match !cache with
| null -> cache := new Dictionary<_, _>(11 (* sz: int *) )
| _ -> ()
!cache
match cache.TryGetValue idx with
| true, v ->
incr count
v
| _ ->
let res = f idx
cache.[idx] <- res
res
//-----------------------------------------------------------------------
// Polymorphic general helpers for searching for particular rows.
// ----------------------------------------------------------------------
let seekFindRow numRows rowChooser =
let mutable i = 1
while (i <= numRows && not (rowChooser i)) do
i <- i + 1
if i > numRows then dprintn "warning: seekFindRow: row not found"
i
// search for rows satisfying predicate
let seekReadIndexedRows (numRows, rowReader, keyFunc, keyComparer, binaryChop, rowConverter) =
if binaryChop then
let mutable low = 0
let mutable high = numRows + 1
begin
let mutable fin = false
while not fin do
if high - low <= 1 then
fin <- true
else
let mid = (low + high) / 2
let midrow = rowReader mid
let c = keyComparer (keyFunc midrow)
if c > 0 then
low <- mid
elif c < 0 then
high <- mid
else
fin <- true
end
let mutable res = []
if high - low > 1 then
// now read off rows, forward and backwards
let mid = (low + high) / 2
// read forward
begin
let mutable fin = false
let mutable curr = mid
while not fin do
if curr > numRows then
fin <- true
else
let currrow = rowReader curr
if keyComparer (keyFunc currrow) = 0 then
res <- rowConverter currrow :: res
else
fin <- true
curr <- curr + 1
done
end
res <- List.rev res
// read backwards
begin
let mutable fin = false
let mutable curr = mid - 1
while not fin do
if curr = 0 then
fin <- true
else
let currrow = rowReader curr
if keyComparer (keyFunc currrow) = 0 then
res <- rowConverter currrow :: res