-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnsafeNativeMethods.cs
executable file
·4542 lines (3928 loc) · 146 KB
/
UnsafeNativeMethods.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
/********************************************************
* ADO.NET 2.0 Data Provider for SQLite Version 3.X
* Written by Robert Simpson (robert@blackcastlesoft.com)
*
* Released to the public domain, use at your own risk!
********************************************************/
namespace System.Data.SQLite
{
using System;
using System.Globalization;
#if !NET_COMPACT_20 && (TRACE_DETECTION || TRACE_SHARED || TRACE_PRELOAD || TRACE_HANDLE)
using System.Diagnostics;
#endif
using System.Collections.Generic;
using System.IO;
using System.Reflection;
#if !PLATFORM_COMPACTFRAMEWORK
using System.Security;
#endif
using System.Runtime.InteropServices;
#if (NET_40 || NET_45 || NET_451 || NET_452 || NET_46 || NET_461 || NET_462) && !PLATFORM_COMPACTFRAMEWORK
using System.Runtime.Versioning;
#endif
#if !PLATFORM_COMPACTFRAMEWORK
using System.Text;
#endif
#if !PLATFORM_COMPACTFRAMEWORK || COUNT_HANDLE
using System.Threading;
#endif
using System.Xml;
#region Debug Data Static Class
#if COUNT_HANDLE || DEBUG
/// <summary>
/// This class encapsulates some tracking data that is used for debugging
/// and testing purposes.
/// </summary>
internal static class DebugData
{
#region Private Data
#region Critical Handle Counts (Debug Build Only)
#if COUNT_HANDLE
//
// NOTE: These counts represent the total number of outstanding
// (non-disposed) CriticalHandle derived object instances
// created by this library and are primarily for use by
// the test suite. These counts are incremented by the
// associated constructors and are decremented upon the
// successful completion of the associated ReleaseHandle
// methods.
//
internal static int connectionCount;
internal static int statementCount;
internal static int backupCount;
internal static int blobCount;
#endif
#endregion
/////////////////////////////////////////////////////////////////////////
#region Settings Read Counts (Debug Build Only)
#if DEBUG
/// <summary>
/// This lock is used to protect the static
/// <see cref="settingReadCounts" /> field.
/// </summary>
private static readonly object staticSyncRoot = new object();
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// This dictionary stores the read counts for the runtime configuration
/// settings. This information is only recorded when compiled in the
/// "Debug" build configuration.
/// </summary>
private static Dictionary<string, int> settingReadCounts;
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// This dictionary stores the read counts for the runtime configuration
/// settings via the XML configuration file. This information is only
/// recorded when compiled in the "Debug" build configuration.
/// </summary>
private static Dictionary<string, int> settingFileReadCounts;
#endif
#endregion
#endregion
/////////////////////////////////////////////////////////////////////////
#region Public Methods
#if DEBUG
/// <summary>
/// Creates dictionaries used to store the read counts for each of
/// the runtime configuration settings. These numbers are used for
/// debugging and testing purposes only.
/// </summary>
public static void InitializeSettingReadCounts()
{
lock (staticSyncRoot)
{
//
// NOTE: Create the dictionaries of statistics that will
// contain the number of times each setting value
// has been read.
//
if (settingReadCounts == null)
settingReadCounts = new Dictionary<string, int>();
if (settingFileReadCounts == null)
settingFileReadCounts = new Dictionary<string, int>();
}
}
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// Increments the read count for the specified runtime configuration
/// setting. These numbers are used for debugging and testing purposes
/// only.
/// </summary>
/// <param name="name">
/// The name of the setting being read.
/// </param>
/// <param name="viaFile">
/// Non-zero if the specified setting is being read from the XML
/// configuration file.
/// </param>
public static void IncrementSettingReadCount(
string name,
bool viaFile
)
{
lock (staticSyncRoot)
{
//
// NOTE: Update statistics for this setting value.
//
if (viaFile)
{
if (settingFileReadCounts != null)
{
int count;
if (settingFileReadCounts.TryGetValue(name, out count))
settingFileReadCounts[name] = count + 1;
else
settingFileReadCounts.Add(name, 1);
}
}
else
{
if (settingReadCounts != null)
{
int count;
if (settingReadCounts.TryGetValue(name, out count))
settingReadCounts[name] = count + 1;
else
settingReadCounts.Add(name, 1);
}
}
}
}
#endif
#endregion
}
#endif
#endregion
/////////////////////////////////////////////////////////////////////////////
#region Helper Methods Static Class
/// <summary>
/// This static class provides some methods that are shared between the
/// native library pre-loader and other classes.
/// </summary>
internal static class HelperMethods
{
#region Private Data
/// <summary>
/// This lock is used to protect the static <see cref="isMono" /> field.
/// </summary>
private static readonly object staticSyncRoot = new object();
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// This type is only present when running on Mono.
/// </summary>
private static readonly string MonoRuntimeType = "Mono.Runtime";
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// Keeps track of whether we are running on Mono. Initially null, it is
/// set by the <see cref="IsMono" /> method on its first call. Later, it
/// is returned verbatim by the <see cref="IsMono" /> method.
/// </summary>
private static bool? isMono = null;
#endregion
/////////////////////////////////////////////////////////////////////////
#region Private Methods
/// <summary>
/// Determines whether or not this assembly is running on Mono.
/// </summary>
/// <returns>
/// Non-zero if this assembly is running on Mono.
/// </returns>
private static bool IsMono()
{
try
{
lock (staticSyncRoot)
{
if (isMono == null)
isMono = (Type.GetType(MonoRuntimeType) != null);
return (bool)isMono;
}
}
catch
{
// do nothing.
}
return false;
}
#endregion
/////////////////////////////////////////////////////////////////////////
#region Internal Methods
/// <summary>
/// Determines if the current process is running on one of the Windows
/// [sub-]platforms.
/// </summary>
/// <returns>
/// Non-zero when running on Windows; otherwise, zero.
/// </returns>
internal static bool IsWindows()
{
PlatformID platformId = Environment.OSVersion.Platform;
if ((platformId == PlatformID.Win32S) ||
(platformId == PlatformID.Win32Windows) ||
(platformId == PlatformID.Win32NT) ||
(platformId == PlatformID.WinCE))
{
return true;
}
return false;
}
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// This is a wrapper around the
/// <see cref="String.Format(IFormatProvider,String,Object[])" /> method.
/// On Mono, it has to call the method overload without the
/// <see cref="IFormatProvider" /> parameter, due to a bug in Mono.
/// </summary>
/// <param name="provider">
/// This is used for culture-specific formatting.
/// </param>
/// <param name="format">
/// The format string.
/// </param>
/// <param name="args">
/// An array the objects to format.
/// </param>
/// <returns>
/// The resulting string.
/// </returns>
internal static string StringFormat(
IFormatProvider provider,
string format,
params object[] args
)
{
if (IsMono())
return String.Format(format, args);
else
return String.Format(provider, format, args);
}
#endregion
}
#endregion
/////////////////////////////////////////////////////////////////////////////
#region Native Library Helper Class
/// <summary>
/// This static class provides a thin wrapper around the native library
/// loading features of the underlying platform.
/// </summary>
internal static class NativeLibraryHelper
{
#region Private Delegates
/// <summary>
/// This delegate is used to wrap the concept of loading a native
/// library, based on a file name, and returning the loaded module
/// handle.
/// </summary>
/// <param name="fileName">
/// The file name of the native library to load.
/// </param>
/// <returns>
/// The native module handle upon success -OR- IntPtr.Zero on failure.
/// </returns>
private delegate IntPtr LoadLibraryCallback(
string fileName
);
#endregion
/////////////////////////////////////////////////////////////////////////
#region Private Methods
/// <summary>
/// Attempts to load the specified native library file using the Win32
/// API.
/// </summary>
/// <param name="fileName">
/// The file name of the native library to load.
/// </param>
/// <returns>
/// The native module handle upon success -OR- IntPtr.Zero on failure.
/// </returns>
private static IntPtr LoadLibraryWin32(
string fileName
)
{
return UnsafeNativeMethodsWin32.LoadLibrary(fileName);
}
/////////////////////////////////////////////////////////////////////////
#if !PLATFORM_COMPACTFRAMEWORK
/// <summary>
/// Attempts to load the specified native library file using the POSIX
/// API.
/// </summary>
/// <param name="fileName">
/// The file name of the native library to load.
/// </param>
/// <returns>
/// The native module handle upon success -OR- IntPtr.Zero on failure.
/// </returns>
private static IntPtr LoadLibraryPosix(
string fileName
)
{
return UnsafeNativeMethodsPosix.dlopen(
fileName, UnsafeNativeMethodsPosix.RTLD_DEFAULT);
}
#endif
#endregion
/////////////////////////////////////////////////////////////////////////
#region Public Methods
/// <summary>
/// Attempts to load the specified native library file.
/// </summary>
/// <param name="fileName">
/// The file name of the native library to load.
/// </param>
/// <returns>
/// The native module handle upon success -OR- IntPtr.Zero on failure.
/// </returns>
public static IntPtr LoadLibrary(
string fileName
)
{
LoadLibraryCallback callback = LoadLibraryWin32;
#if !PLATFORM_COMPACTFRAMEWORK
if (!HelperMethods.IsWindows())
callback = LoadLibraryPosix;
#endif
return callback(fileName);
}
#endregion
}
#endregion
/////////////////////////////////////////////////////////////////////////////
#region Unmanaged Interop Methods Static Class (POSIX)
#if !PLATFORM_COMPACTFRAMEWORK
/// <summary>
/// This class declares P/Invoke methods to call native POSIX APIs.
/// </summary>
[SuppressUnmanagedCodeSecurity]
internal static class UnsafeNativeMethodsPosix
{
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// This is the P/Invoke method that wraps the native Unix dlopen
/// function. See the POSIX documentation for full details on what it
/// does.
/// </summary>
/// <param name="fileName">
/// The name of the executable library.
/// </param>
/// <param name="mode">
/// This must be a combination of the individual bit flags RTLD_LAZY,
/// RTLD_NOW, RTLD_GLOBAL, and/or RTLD_LOCAL.
/// </param>
/// <returns>
/// The native module handle upon success -OR- IntPtr.Zero on failure.
/// </returns>
[DllImport("__Internal", EntryPoint = "dlopen",
CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi,
BestFitMapping = false, ThrowOnUnmappableChar = true,
SetLastError = true)]
internal static extern IntPtr dlopen(string fileName, int mode);
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// For use with dlopen(), bind function calls lazily.
/// </summary>
internal const int RTLD_LAZY = 0x1;
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// For use with dlopen(), bind function calls immediately.
/// </summary>
internal const int RTLD_NOW = 0x2;
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// For use with dlopen(), make symbols globally available.
/// </summary>
internal const int RTLD_GLOBAL = 0x100;
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// For use with dlopen(), opposite of RTLD_GLOBAL, and the default.
/// </summary>
internal const int RTLD_LOCAL = 0x000;
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// For use with dlopen(), the defaults used by this class.
/// </summary>
internal const int RTLD_DEFAULT = RTLD_NOW | RTLD_GLOBAL;
}
#endif
#endregion
/////////////////////////////////////////////////////////////////////////////
#region Unmanaged Interop Methods Static Class (Win32)
/// <summary>
/// This class declares P/Invoke methods to call native Win32 APIs.
/// </summary>
#if !PLATFORM_COMPACTFRAMEWORK
[SuppressUnmanagedCodeSecurity]
#endif
internal static class UnsafeNativeMethodsWin32
{
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// This is the P/Invoke method that wraps the native Win32 LoadLibrary
/// function. See the MSDN documentation for full details on what it
/// does.
/// </summary>
/// <param name="fileName">
/// The name of the executable library.
/// </param>
/// <returns>
/// The native module handle upon success -OR- IntPtr.Zero on failure.
/// </returns>
#if !PLATFORM_COMPACTFRAMEWORK
[DllImport("kernel32",
#else
[DllImport("coredll",
#endif
CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Auto,
#if !PLATFORM_COMPACTFRAMEWORK
BestFitMapping = false, ThrowOnUnmappableChar = true,
#endif
SetLastError = true)]
internal static extern IntPtr LoadLibrary(string fileName);
/////////////////////////////////////////////////////////////////////////
#if PLATFORM_COMPACTFRAMEWORK
/// <summary>
/// This is the P/Invoke method that wraps the native Win32 GetSystemInfo
/// function. See the MSDN documentation for full details on what it
/// does.
/// </summary>
/// <param name="systemInfo">
/// The system information structure to be filled in by the function.
/// </param>
[DllImport("coredll", CallingConvention = CallingConvention.Winapi)]
internal static extern void GetSystemInfo(out SYSTEM_INFO systemInfo);
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// This enumeration contains the possible values for the processor
/// architecture field of the system information structure.
/// </summary>
internal enum ProcessorArchitecture : ushort /* COMPAT: Win32. */
{
Intel = 0,
MIPS = 1,
Alpha = 2,
PowerPC = 3,
SHx = 4,
ARM = 5,
IA64 = 6,
Alpha64 = 7,
MSIL = 8,
AMD64 = 9,
IA32_on_Win64 = 10,
Unknown = 0xFFFF
}
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// This structure contains information about the current computer. This
/// includes the processor type, page size, memory addresses, etc.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct SYSTEM_INFO
{
public ProcessorArchitecture wProcessorArchitecture;
public ushort wReserved; /* NOT USED */
public uint dwPageSize; /* NOT USED */
public IntPtr lpMinimumApplicationAddress; /* NOT USED */
public IntPtr lpMaximumApplicationAddress; /* NOT USED */
public uint dwActiveProcessorMask; /* NOT USED */
public uint dwNumberOfProcessors; /* NOT USED */
public uint dwProcessorType; /* NOT USED */
public uint dwAllocationGranularity; /* NOT USED */
public ushort wProcessorLevel; /* NOT USED */
public ushort wProcessorRevision; /* NOT USED */
}
#endif
}
#endregion
/////////////////////////////////////////////////////////////////////////////
#region Unmanaged Interop Methods Static Class (SQLite)
/// <summary>
/// This class declares P/Invoke methods to call native SQLite APIs.
/// </summary>
#if !PLATFORM_COMPACTFRAMEWORK
[SuppressUnmanagedCodeSecurity]
#endif
internal static class UnsafeNativeMethods
{
#region Shared Native SQLite Library Pre-Loading Code
#region Private Constants
/// <summary>
/// The file extension used for dynamic link libraries.
/// </summary>
private static readonly string DllFileExtension = ".dll";
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// The file extension used for the XML configuration file.
/// </summary>
private static readonly string ConfigFileExtension = ".config";
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// This is the name of the XML configuration file specific to the
/// System.Data.SQLite assembly.
/// </summary>
private static readonly string XmlConfigFileName =
typeof(UnsafeNativeMethods).Namespace + DllFileExtension +
ConfigFileExtension;
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// This is the XML configuratrion file token that will be replaced with
/// the qualified path to the directory containing the XML configuration
/// file.
/// </summary>
private static readonly string XmlConfigDirectoryToken =
"%PreLoadSQLite_XmlConfigDirectory%";
#endregion
/////////////////////////////////////////////////////////////////////////
#region Private Constants (Desktop Framework Only)
#if !PLATFORM_COMPACTFRAMEWORK
/// <summary>
/// This is the environment variable token that will be replaced with
/// the qualified path to the directory containing this assembly.
/// </summary>
private static readonly string AssemblyDirectoryToken =
"%PreLoadSQLite_AssemblyDirectory%";
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// This is the environment variable token that will be replaced with an
/// abbreviation of the target framework attribute value associated with
/// this assembly.
/// </summary>
private static readonly string TargetFrameworkToken =
"%PreLoadSQLite_TargetFramework%";
#endif
#endregion
/////////////////////////////////////////////////////////////////////////
#region Private Data
/// <summary>
/// This lock is used to protect the static _SQLiteNativeModuleFileName,
/// _SQLiteNativeModuleHandle, and processorArchitecturePlatforms fields.
/// </summary>
private static readonly object staticSyncRoot = new object();
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// This dictionary stores the mappings between processor architecture
/// names and platform names. These mappings are now used for two
/// purposes. First, they are used to determine if the assembly code
/// base should be used instead of the location, based upon whether one
/// or more of the named sub-directories exist within the assembly code
/// base. Second, they are used to assist in loading the appropriate
/// SQLite interop assembly into the current process.
/// </summary>
private static Dictionary<string, string> processorArchitecturePlatforms;
#endregion
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// For now, this method simply calls the Initialize method.
/// </summary>
static UnsafeNativeMethods()
{
Initialize();
}
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// Attempts to initialize this class by pre-loading the native SQLite
/// library for the processor architecture of the current process.
/// </summary>
internal static void Initialize()
{
#if SQLITE_STANDARD || USE_INTEROP_DLL || PLATFORM_COMPACTFRAMEWORK
#if PRELOAD_NATIVE_LIBRARY
//
// NOTE: If the "No_PreLoadSQLite" environment variable is set (to
// anything), skip all our special code and simply return.
//
if (GetSettingValue("No_PreLoadSQLite", null) != null)
return;
#endif
#endif
#region Debug Build Only
#if DEBUG
//
// NOTE: Create the list of statistics that will contain the
// number of times each setting value has been read.
//
DebugData.InitializeSettingReadCounts();
#endif
#endregion
lock (staticSyncRoot)
{
//
// TODO: Make sure this list is updated if the supported
// processor architecture names and/or platform names
// changes.
//
if (processorArchitecturePlatforms == null)
{
//
// NOTE: Create the map of processor architecture names
// to platform names using a case-insensitive string
// comparer.
//
processorArchitecturePlatforms =
new Dictionary<string, string>(
StringComparer.OrdinalIgnoreCase);
//
// NOTE: Setup the list of platform names associated with
// the supported processor architectures.
//
processorArchitecturePlatforms.Add("x86", "Win32");
processorArchitecturePlatforms.Add("AMD64", "x64");
processorArchitecturePlatforms.Add("IA64", "Itanium");
processorArchitecturePlatforms.Add("ARM", "WinCE");
}
#if SQLITE_STANDARD || USE_INTEROP_DLL || PLATFORM_COMPACTFRAMEWORK
#if PRELOAD_NATIVE_LIBRARY
//
// BUGBUG: What about other application domains?
//
if (_SQLiteNativeModuleHandle == IntPtr.Zero)
{
string baseDirectory = null;
string processorArchitecture = null;
/* IGNORED */
SearchForDirectory(
ref baseDirectory, ref processorArchitecture);
//
// NOTE: Attempt to pre-load the SQLite core library (or
// interop assembly) and store both the file name
// and native module handle for later usage.
//
/* IGNORED */
PreLoadSQLiteDll(
baseDirectory, processorArchitecture,
ref _SQLiteNativeModuleFileName,
ref _SQLiteNativeModuleHandle);
}
#endif
#endif
}
}
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// Combines two path strings.
/// </summary>
/// <param name="path1">
/// The first path -OR- null.
/// </param>
/// <param name="path2">
/// The second path -OR- null.
/// </param>
/// <returns>
/// The combined path string -OR- null if both of the original path
/// strings are null.
/// </returns>
private static string MaybeCombinePath(
string path1,
string path2
)
{
if (path1 != null)
{
if (path2 != null)
return Path.Combine(path1, path2);
else
return path1;
}
else
{
if (path2 != null)
return path2;
else
return null;
}
}
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// Queries and returns the XML configuration file name for the assembly
/// containing the managed System.Data.SQLite components.
/// </summary>
/// <returns>
/// The XML configuration file name -OR- null if it cannot be determined
/// or does not exist.
/// </returns>
private static string GetXmlConfigFileName()
{
string directory;
string fileName;
#if !PLATFORM_COMPACTFRAMEWORK
directory = AppDomain.CurrentDomain.BaseDirectory;
fileName = MaybeCombinePath(directory, XmlConfigFileName);
if (File.Exists(fileName))
return fileName;
#endif
directory = GetAssemblyDirectory();
fileName = MaybeCombinePath(directory, XmlConfigFileName);
if (File.Exists(fileName))
return fileName;
return null;
}
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// If necessary, replaces all supported XML configuration file tokens
/// with their associated values.
/// </summary>
/// <param name="fileName">
/// The name of the XML configuration file being read.
/// </param>
/// <param name="value">
/// A setting value read from the XML configuration file.
/// </param>
/// <returns>
/// The value of the <paramref name="value" /> will all supported XML
/// configuration file tokens replaced. No return value is reserved
/// to indicate an error. This method cannot fail.
/// </returns>
private static string ReplaceXmlConfigFileTokens(
string fileName,
string value
)
{
if (!String.IsNullOrEmpty(value))
{
if (!String.IsNullOrEmpty(fileName))
{
try
{
string directory = Path.GetDirectoryName(fileName);
if (!String.IsNullOrEmpty(directory))
{
value = value.Replace(
XmlConfigDirectoryToken, directory);
}
}
#if !NET_COMPACT_20 && TRACE_SHARED
catch (Exception e)
#else
catch (Exception)
#endif
{
#if !NET_COMPACT_20 && TRACE_SHARED
try
{
Trace.WriteLine(HelperMethods.StringFormat(
CultureInfo.CurrentCulture, "Native library " +
"pre-loader failed to replace XML " +
"configuration file \"{0}\" tokens: {1}",
fileName, e)); /* throw */
}
catch
{
// do nothing.
}
#endif
}
}
}
return value;
}
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// Queries and returns the value of the specified setting, using the
/// specified XML configuration file.
/// </summary>
/// <param name="fileName">
/// The name of the XML configuration file to read.
/// </param>
/// <param name="name">
/// The name of the setting.
/// </param>
/// <param name="default">
/// The value to be returned if the setting has not been set explicitly
/// or cannot be determined.
/// </param>
/// <param name="expand">
/// Non-zero to expand any environment variable references contained in
/// the setting value to be returned. This has no effect on the .NET
/// Compact Framework.
/// </param>
/// <returns>
/// The value of the setting -OR- the default value specified by
/// <paramref name="default" /> if it has not been set explicitly or
/// cannot be determined.
/// </returns>
private static string GetSettingValueViaXmlConfigFile(
string fileName, /* in */
string name, /* in */
string @default, /* in */
bool expand /* in */
)
{
try
{
if ((fileName == null) || (name == null))
return @default;
XmlDocument document = new XmlDocument();
document.Load(fileName); /* throw */
XmlElement element = document.SelectSingleNode(
HelperMethods.StringFormat(CultureInfo.InvariantCulture,
"/configuration/appSettings/add[@key='{0}']", name)) as
XmlElement; /* throw */
if (element != null)
{
string value = null;
if (element.HasAttribute("value"))
value = element.GetAttribute("value");
if (!String.IsNullOrEmpty(value))
{
#if !PLATFORM_COMPACTFRAMEWORK
if (expand)
value = Environment.ExpandEnvironmentVariables(value);
value = ReplaceEnvironmentVariableTokens(value);
#endif
value = ReplaceXmlConfigFileTokens(fileName, value);
}
if (value != null)
return value;
}
}
#if !NET_COMPACT_20 && TRACE_SHARED
catch (Exception e)
#else
catch (Exception)
#endif
{
#if !NET_COMPACT_20 && TRACE_SHARED
try
{
Trace.WriteLine(HelperMethods.StringFormat(
CultureInfo.CurrentCulture, "Native library " +
"pre-loader failed to get setting \"{0}\" value " +
"from XML configuration file \"{1}\": {2}", name,
fileName, e)); /* throw */
}
catch
{
// do nothing.
}
#endif
}
return @default;
}
/////////////////////////////////////////////////////////////////////////
#if !PLATFORM_COMPACTFRAMEWORK
/// <summary>
/// Attempts to determine the target framework attribute value that is
/// associated with the specified managed assembly, if applicable.
/// </summary>
/// <param name="assembly">
/// The managed assembly to read the target framework attribute value
/// from.
/// </param>
/// <returns>
/// The value of the target framework attribute value for the specified
/// managed assembly -OR- null if it cannot be determined. If this
/// assembly was compiled with a version of the .NET Framework prior to
/// version 4.0, the value returned MAY reflect that version of the .NET
/// Framework instead of the one associated with the specified managed
/// assembly.
/// </returns>
private static string GetAssemblyTargetFramework(
Assembly assembly
)
{
if (assembly != null)
{
#if NET_40 || NET_45 || NET_451 || NET_452 || NET_46 || NET_461 || NET_462
try
{
if (assembly.IsDefined(
typeof(TargetFrameworkAttribute), false))
{
TargetFrameworkAttribute targetFramework =
(TargetFrameworkAttribute)
assembly.GetCustomAttributes(
typeof(TargetFrameworkAttribute), false)[0];
return targetFramework.FrameworkName;
}
}