System.Data.SQLite

Check-in [5c0646db9d]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Prevent returning a connection handle whose finalizer may be pending on the GC thread. Part of fix for ticket [996d13cd87]. Also, update Eagle in externals to latest trunk.
Downloads: Tarball | ZIP archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: 5c0646db9d326095304e868e25c0c2d02e1a8bc9
User & Date: mistachkin 2012-05-04 16:04:32.128
Context
2012-05-04
18:28
Make sure to check for a null connection handle prior to calling the GC.SuppressFinalize method. check-in: 5cc9167d46 user: mistachkin tags: trunk
16:04
Prevent returning a connection handle whose finalizer may be pending on the GC thread. Part of fix for ticket [996d13cd87]. Also, update Eagle in externals to latest trunk. check-in: 5c0646db9d user: mistachkin tags: trunk
2012-05-03
19:21
Check each weak reference object from the queue prior to attempting to fetch its target. check-in: 2a6ee97694 user: mistachkin tags: trunk
Changes
Side-by-Side Diff Ignore Whitespace Patch
Changes to Externals/Eagle/bin/Eagle.dll.

cannot compute difference between binary files

Changes to Externals/Eagle/bin/EagleShell.exe.

cannot compute difference between binary files

Changes to Externals/Eagle/bin/EagleShell.exe.config.
1
2
3
4
5
6

7
8
9
10
11
12
13
1
2
3
4
5

6
7
8
9
10
11
12
13





-
+







<?xml version="1.0" encoding="UTF-8" ?>
<!--
 *
 * EagleShell.exe.config -
 *
 * Copyright (c) 2007-2010 by Joe Mistachkin.  All rights reserved.
 * Copyright (c) 2007-2012 by Joe Mistachkin.  All rights reserved.
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 * RCS: @(#) $Id: $
 *
-->
Changes to Externals/Eagle/bin/EagleShell.exe.mda.config.
1
2
3
4
5
6

7
8
9
10
11
12
13
1
2
3
4
5

6
7
8
9
10
11
12
13





-
+







<?xml version="1.0" encoding="UTF-8" ?>
<!--
 *
 * EagleShell.exe.mda.config -
 *
 * Copyright (c) 2007-2010 by Joe Mistachkin.  All rights reserved.
 * Copyright (c) 2007-2012 by Joe Mistachkin.  All rights reserved.
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 * RCS: @(#) $Id: $
 *
-->
Changes to Externals/Eagle/lib/Eagle1.0/vendor.eagle.
109
110
111
112
113
114
115
116

117
118
119
120
121
122
123
109
110
111
112
113
114
115

116
117
118
119
120
121
122
123







-
+







            #
            lappend ::env(EAGLELIBPATH) $dir2

            #
            # NOTE: Force Eagle to rebuild the auto-path list for the current
            #       interpreter right now.
            #
            object invoke Utility RefreshAutoPathList
            object invoke Utility RefreshAutoPathList true
          }

          #
          # NOTE: We are done, return success.
          #
          return true
        }
Changes to System.Data.SQLite/SQLiteBase.cs.
345
346
347
348
349
350
351


352
353


354
355
356
357
358
359
360
361
362
363
345
346
347
348
349
350
351
352
353


354
355
356


357
358
359
360
361
362
363







+
+
-
-
+
+

-
-







    // Therefore these functions have to be static, and have to be low-level.

    internal static string GetLastError(SQLiteConnectionHandle hdl, IntPtr db)
    {
        if ((hdl == null) || (db == IntPtr.Zero))
            return "null connection or database handle";

        lock (hdl)
        {
        if (hdl.IsClosed || hdl.IsInvalid)
            return "closed or invalid connection handle";
            if (hdl.IsClosed || hdl.IsInvalid)
                return "closed or invalid connection handle";

        lock (hdl)
        {
#if !SQLITE_STANDARD
            int len;
            return UTF8ToString(UnsafeNativeMethods.sqlite3_errmsg_interop(db, out len), len);
#else
            return UTF8ToString(UnsafeNativeMethods.sqlite3_errmsg(db), -1);
#endif
        }
Changes to System.Data.SQLite/SQLiteConnectionPool.cs.
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
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







+
+
+
+
+
+
+
+
+
+
-
-
-
+
+
+

-
-
+
+

-
-
-
-
-
-
-
+
+
+
+
+
+
+

-
-
+
+

-
-
-
+
+
+

-
+

-
-
-
+
+
+
+



-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
-
+
+







    /// </summary>
    /// <param name="fileName">The filename for a desired connection</param>
    /// <param name="maxPoolSize">The maximum size the connection pool for the filename can be</param>
    /// <param name="version">The pool version the returned connection will belong to</param>
    /// <returns>Returns NULL if no connections were available.  Even if none are, the poolversion will still be a valid pool version</returns>
    internal static SQLiteConnectionHandle Remove(string fileName, int maxPoolSize, out int version)
    {
        Queue<WeakReference> poolQueue;

        //
        // NOTE: This lock cannot be held while checking the queue for available
        //       connections because other methods of this class are called from
        //       the GC finalizer thread and we use the WaitForPendingFinalizers
        //       method (below).  Holding this lock while calling that method
        //       would therefore result in a deadlock.  This lock is held while
        //       a temporary copy of the queue is created.
        //
      lock (_connections)
      {
        Pool queue;
        lock (_connections)
        {
            Pool queue;

        // Default to the highest pool version
        version = _poolVersion;
            // Default to the highest pool version
            version = _poolVersion;

        // If we didn't find a pool for this file, create one even though it will be empty.
        // We have to do this here because otherwise calling ClearPool() on the file will not work for active connections
        // that have never seen the pool yet.
        if (_connections.TryGetValue(fileName, out queue) == false)
        {
          queue = new Pool(_poolVersion, maxPoolSize);
          _connections.Add(fileName, queue);
            // If we didn't find a pool for this file, create one even though it will be empty.
            // We have to do this here because otherwise calling ClearPool() on the file will not work for active connections
            // that have never seen the pool yet.
            if (_connections.TryGetValue(fileName, out queue) == false)
            {
                queue = new Pool(_poolVersion, maxPoolSize);
                _connections.Add(fileName, queue);

          return null;
        }
                return null;
            }

        // We found a pool for this file, so use its version number
        version = queue.PoolVersion;
        queue.MaxPoolSize = maxPoolSize;
            // We found a pool for this file, so use its version number
            version = queue.PoolVersion;
            queue.MaxPoolSize = maxPoolSize;

        ResizePool(queue, false);
            ResizePool(queue, false);

        // Try and get a pooled connection from the queue
        Queue<WeakReference> poolQueue = queue.Queue;
        if (poolQueue == null) return null;
            // Try and get a pooled connection from the queue
            poolQueue = new Queue<WeakReference>(queue.Queue);
            if (poolQueue == null) return null;
        }

        while (poolQueue.Count > 0)
        {
          WeakReference cnn = poolQueue.Dequeue();
          if (cnn == null) continue;
          SQLiteConnectionHandle hdl = cnn.Target as SQLiteConnectionHandle;
          if ((hdl != null) && !hdl.IsClosed && !hdl.IsInvalid)
          {
            Interlocked.Increment(ref _poolOpened);
            return hdl;
          }
          cnn.Target = null;
          GC.KeepAlive(hdl);
            WeakReference cnn = poolQueue.Dequeue();
            if (cnn == null) continue;
            SQLiteConnectionHandle hdl = cnn.Target as SQLiteConnectionHandle;

            //
            // BUGFIX: For ticket [996d13cd87], step #1.  After this point,
            //         make sure that the finalizer for the connection handle
            //         just obtained from the queue cannot START running (i.e.
            //         it may still be pending but it will no longer start
            //         after this point).
            //
            GC.SuppressFinalize(hdl);

            try
            {
                //
                // BUGFIX: For ticket [996d13cd87], step #2.  Now, we must wait
                //         for all pending finalizers which have STARTED running
                //         and have not yet COMPLETED.  This must be done just
                //         in case the finalizer for the connection handle just
                //         obtained from the queue has STARTED running at some
                //         point before SuppressFinalize was called on it.
                //
                //         After this point, checking properties of the
                //         connection handle (e.g. IsClosed) should work
                //         reliably without having to worry that they will
                //         (due to the finalizer) change out from under us.
                //
                GC.WaitForPendingFinalizers();

                //
                // BUGFIX: For ticket [996d13cd87], step #3.  Next, verify that
                //         the connection handle is actually valid and [still?]
                //         not closed prior to actually returning it to our
                //         caller.
                //
                if ((hdl != null) && !hdl.IsClosed && !hdl.IsInvalid)
                {
                    Interlocked.Increment(ref _poolOpened);
                    return hdl;
                }
            }
            finally
            {
                //
                // BUGFIX: For ticket [996d13cd87], step #4.  Finally, we must
                //         re-register the connection handle for finalization
                //         now that we have a strong reference to it (i.e. the
                //         finalizer run at least until the connection is
                //         subsequently closed).
                //
                GC.ReRegisterForFinalize(hdl);
            }

#pragma warning disable 162
            GC.KeepAlive(hdl); /* NOTE: Unreachable code. */
#pragma warning restore 162
        }
        return null;
      }

        return null;
    }

    /// <summary>
    /// Clears out all pooled connections and rev's up the default pool version to force all old active objects
    /// not in the pool to get discarded rather than returned to their pools.
    /// </summary>
    internal static void ClearAllPools()
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
241
242
243
244
245
246
247

248
249
250
251
252
253
254







-







            WeakReference cnn = poolQueue.Dequeue();
            if (cnn == null) continue;
            SQLiteConnectionHandle hdl = cnn.Target as SQLiteConnectionHandle;
            if (hdl != null)
            {
              hdl.Dispose();
            }
            cnn.Target = null;
            GC.KeepAlive(hdl);
          }
          
          // Keep track of the highest revision so we can go one higher when we're finished
          if (_poolVersion <= pair.Value.PoolVersion)
            _poolVersion = pair.Value.PoolVersion + 1;
        }
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
282
283
284
285
286
287
288

289
290
291
292
293
294
295







-







            WeakReference cnn = poolQueue.Dequeue();
            if (cnn == null) continue;
            SQLiteConnectionHandle hdl = cnn.Target as SQLiteConnectionHandle;
            if (hdl != null)
            {
              hdl.Dispose();
            }
            cnn.Target = null;
            GC.KeepAlive(hdl);
          }
        }
      }
    }

    /// <summary>
290
291
292
293
294
295
296
297
298
299
300
301
302
346
347
348
349
350
351
352

353
354
355
356
357







-





        WeakReference cnn = poolQueue.Dequeue();
        if (cnn == null) continue;
        SQLiteConnectionHandle hdl = cnn.Target as SQLiteConnectionHandle;
        if (hdl != null)
        {
          hdl.Dispose();
        }
        cnn.Target = null;
        GC.KeepAlive(hdl);
      }
    }
  }
}
Changes to Tests/tkt-996d13cd87.eagle.
23
24
25
26
27
28
29

30
31


32
33
34










35
36
37
38
39
40
41
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







+
-
-
+
+

-
-
+
+
+
+
+
+
+
+
+
+







for {set i 1} {$i < 3} {incr i} {
  set pooling [expr {$i == 2 ? True : False}]

  runTest {test [appendArgs tkt-996d13cd87-1. $i] {SQLiteConnection stress} \
      -setup {
    set fileName [appendArgs tkt-996d13cd87-1. $i .db]

    if {[catch {
    object invoke -flags +NonPublic \
        System.Data.SQLite.SQLiteConnectionPool _poolOpened 0
        object invoke -flags +NonPublic \
            System.Data.SQLite.SQLiteConnectionPool _poolOpened 0

    object invoke -flags +NonPublic \
        System.Data.SQLite.SQLiteConnectionPool _poolClosed 0
        object invoke -flags +NonPublic \
            System.Data.SQLite.SQLiteConnectionPool _poolClosed 0
    }] == 0} then {
      set havePoolCounts true
    } else {
      set havePoolCounts false

      tputs $test_channel [appendArgs \
          "==== WARNING: connection pool counts are not available\n"]
    }
  } -body {
    set id [object invoke Interpreter.GetActive NextId]
    set dataSource [file join [getDatabaseDirectory] $fileName]

    set sql { \
      CREATE TABLE t1(x TEXT); \
      INSERT INTO t1 (x) VALUES(RANDOMBLOB(1000)); \
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
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







-
+


-
-
+
+
+


-
+
+






-
+
+













    }] true true true results errors System.Data.SQLite.dll]

    list $code $results \
        [expr {[info exists errors] ? $errors : ""}] \
        [expr {$code eq "Ok" ? [catch {
          object invoke _Dynamic${id}.Test${id} Main
        } result] : [set result ""]}] $result \
        [expr {$pooling ? [object invoke -flags +NonPublic \
        [expr {$havePoolCounts ? $pooling ? [object invoke -flags +NonPublic \
            System.Data.SQLite.SQLiteConnectionPool _poolOpened] > 0 : \
            [object invoke -flags +NonPublic \
            System.Data.SQLite.SQLiteConnectionPool _poolOpened] == 0}] \
        [expr {$pooling ? [object invoke -flags +NonPublic \
            System.Data.SQLite.SQLiteConnectionPool _poolOpened] == 0} : \
            True] \
        [expr {$havePoolCounts ? $pooling ? [object invoke -flags +NonPublic \
            System.Data.SQLite.SQLiteConnectionPool _poolClosed] > 0 : \
            [object invoke -flags +NonPublic \
            System.Data.SQLite.SQLiteConnectionPool _poolClosed] == 0}]
            System.Data.SQLite.SQLiteConnectionPool _poolClosed] == 0} : \
            True]
  } -cleanup {
    object invoke System.Data.SQLite.SQLiteConnection ClearAllPools
    object invoke GC GetTotalMemory true

    cleanupDb $fileName

    unset -nocomplain result results errors code sql dataSource id db fileName
    unset -nocomplain result results errors code sql dataSource id db \
        havePoolCounts fileName
  } -constraints {eagle monoBug28 command.sql compile.DATA\
SQLite System.Data.SQLite} -match regexp -result {^Ok\
System#CodeDom#Compiler#CompilerResults#\d+ \{\} 0 \d+ True True$}}
}

###############################################################################

unset -nocomplain pooling i

###############################################################################

runSQLiteTestEpilogue
runTestEpilogue