text:
// Copyright © Microsoft Open Technologies, Inc.
// All Rights Reserved
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache 2 License for the specific language governing permissions and limitations under the License.

namespace SQLitePCL
{
    using System;
    using System.Collections.Generic;
    using System.Runtime.InteropServices;
#if PLATFORM_IOS
    using MonoTouch;
#elif PLATFORM_UNIFIED
    using ObjCRuntime;
#endif

    /// <summary>
    /// Implements the <see cref="ISQLite3Provider"/> interface
    /// </summary>
#if __ANDROID__
    [Android.Runtime.Preserve(AllMembers=true)]
#elif PLATFORM_IOS
	[MonoTouch.Foundation.Preserve(AllMembers = true)]
#elif PLATFORM_UNIFIED
	[Foundation.Preserve(AllMembers = true)]
#endif
    public sealed class SQLite3Provider_REPLACE_WITH_SIMPLE_DLL_NAME : ISQLite3Provider
    {
	    // this file is intended to be compiled only after
	    // an automatic search-and-replace has been done.
	    //
	    // TODO it would be nice to make this file error
	    // at compile time when the replace has not been performed.

        public SQLite3Provider_REPLACE_WITH_SIMPLE_DLL_NAME()
        {
#if NETFX_CORE
            // FYI, the wp8 code does this same thing except using PRAGMAs

        // TODO these two calls are a problem.  they end up calling sqlite3_initialize()
        // which means the app never gets a chance to call sqlite3_config().
		NativeMethods.sqlite3_win32_set_directory(/*data directory type*/1, Windows.Storage.ApplicationData.Current.LocalFolder.Path);
		NativeMethods.sqlite3_win32_set_directory(/*temp directory type*/2, Windows.Storage.ApplicationData.Current.TemporaryFolder.Path);
#endif
        }

        int ISQLite3Provider.sqlite3_win32_set_directory(int typ, string path)
        {
#if NETFX_CORE
            return NativeMethods.sqlite3_win32_set_directory((uint) typ, path);
#else
            throw new NotImplementedException();
#endif
        }

        int ISQLite3Provider.sqlite3_open(string filename, out IntPtr db)
        {
            return NativeMethods.sqlite3_open(util.to_utf8(filename), out db);
        }

        int ISQLite3Provider.sqlite3_open_v2(string filename, out IntPtr db, int flags, string vfs)
        {
            return NativeMethods.sqlite3_open_v2(util.to_utf8(filename), out db, flags, util.to_utf8(vfs));
        }

    #pragma warning disable 649
    private struct sqlite3_vfs
    {
        public int iVersion;
        public int szOsFile;
        public int mxPathname;
        public IntPtr pNext;
        public IntPtr zName;
        public IntPtr pAppData;
        public IntPtr xOpen;
        public SQLiteDeleteDelegate xDelete;
        public IntPtr xAccess;
        public IntPtr xFullPathname;
        public IntPtr xDlOpen;
        public IntPtr xDlError;
        public IntPtr xDlSym;
        public IntPtr xDlClose;
        public IntPtr xRandomness;
        public IntPtr xSleep;
        public IntPtr xCurrentTime;
        public IntPtr xGetLastError;

        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
        public delegate int SQLiteDeleteDelegate(IntPtr pVfs, byte[] zName, int syncDir);
    }
    #pragma warning restore 649

	int ISQLite3Provider.sqlite3__vfs__delete(string vfs, string filename, int syncDir)
	{
	    IntPtr ptrVfs = NativeMethods.sqlite3_vfs_find(util.to_utf8(vfs));
	    // this code and the struct it uses was taken from aspnet/DataCommon.SQLite, Apache License 2.0
	    sqlite3_vfs vstruct = (sqlite3_vfs) Marshal.PtrToStructure(ptrVfs, typeof(sqlite3_vfs));
	    return vstruct.xDelete(ptrVfs, util.to_utf8(filename), 1);
	}

        int ISQLite3Provider.sqlite3_close_v2(IntPtr db)
        {
            var rc = NativeMethods.sqlite3_close_v2(db);
		hooks.removeFor(db);
		return rc;
        }

        int ISQLite3Provider.sqlite3_close(IntPtr db)
        {
            var rc = NativeMethods.sqlite3_close(db);
		hooks.removeFor(db);
		return rc;
        }

        int ISQLite3Provider.sqlite3_enable_shared_cache(int enable)
        {
            return NativeMethods.sqlite3_enable_shared_cache(enable);
        }

        void ISQLite3Provider.sqlite3_interrupt(IntPtr db)
        {
            NativeMethods.sqlite3_interrupt(db);
        }

        void ISQLite3Provider.sqlite3_activate_cerod(byte[] passPhrase)
        {
            NativeMethods.sqlite3_activate_cerod(passPhrase);
        }

        void ISQLite3Provider.sqlite3_activate_see(byte[] passPhrase)
        {
            NativeMethods.sqlite3_activate_see(passPhrase);
        }

#if PLATFORM_IOS || PLATFORM_UNIFIED
        [MonoPInvokeCallback (typeof(NativeMethods.callback_exec))] // TODO not xplat
#endif
        static int exec_hook_bridge(IntPtr p, int n, IntPtr values_ptr, IntPtr names_ptr)
        {
            exec_hook_info hi = exec_hook_info.from_ptr(p);
            return hi.call(n, values_ptr, names_ptr);
        }

        int ISQLite3Provider.sqlite3_exec(IntPtr db, string sql, delegate_exec func, object user_data, out string errMsg)
        {
            IntPtr errmsg_ptr;
            int rc;

            if (func != null)
            {
                exec_hook_info hi = new exec_hook_info(func, user_data);
                rc = NativeMethods.sqlite3_exec(db, util.to_utf8(sql), exec_hook_bridge, hi.ptr, out errmsg_ptr);
                hi.free();
            }
            else
            {
                rc = NativeMethods.sqlite3_exec(db, util.to_utf8(sql), null, IntPtr.Zero, out errmsg_ptr);
            }

            if (errmsg_ptr == IntPtr.Zero)
            {
                errMsg = null;
            }
            else
            {
                errMsg = util.from_utf8(errmsg_ptr);
                NativeMethods.sqlite3_free(errmsg_ptr);
            }

            return rc;
        }

        int ISQLite3Provider.sqlite3_complete(string sql)
        {
            return NativeMethods.sqlite3_complete(util.to_utf8(sql));
        }

        string ISQLite3Provider.sqlite3_compileoption_get(int n)
        {
            return util.from_utf8(NativeMethods.sqlite3_compileoption_get(n));
        }

        int ISQLite3Provider.sqlite3_compileoption_used(string s)
        {
            return NativeMethods.sqlite3_compileoption_used(util.to_utf8(s));
        }

        int ISQLite3Provider.sqlite3_table_column_metadata(IntPtr db, string dbName, string tblName, string colName, out string dataType, out string collSeq, out int notNull, out int primaryKey, out int autoInc)
        {
            IntPtr datatype_ptr;
            IntPtr collseq_ptr;

            int rc = NativeMethods.sqlite3_table_column_metadata(
                        db, util.to_utf8(dbName), util.to_utf8(tblName), util.to_utf8(colName),
                        out datatype_ptr, out collseq_ptr, out notNull, out primaryKey, out autoInc);

            if (datatype_ptr == IntPtr.Zero)
            {
                dataType = null;
            }
            else
            {
                dataType = util.from_utf8(datatype_ptr);
                if (dataType.Length == 0)
                {
                    dataType = null;
                }
            }

            if (collseq_ptr == IntPtr.Zero)
            {
                collSeq = null;
            }
            else
            {
                collSeq = util.from_utf8(collseq_ptr);
                if (collSeq.Length == 0)
                {
                    collSeq = null;
                }
            }

            return rc;
        }

        int ISQLite3Provider.sqlite3_prepare_v2(IntPtr db, string sql, out IntPtr stm, out string remain)
        {
            var ba_sql = util.to_utf8(sql);
            GCHandle pinned_sql = GCHandle.Alloc(ba_sql, GCHandleType.Pinned);
            IntPtr ptr_sql = pinned_sql.AddrOfPinnedObject();
            IntPtr tail;
            int rc = NativeMethods.sqlite3_prepare_v2(db, ptr_sql, -1, out stm, out tail);
            if (tail == IntPtr.Zero)
            {
                remain = null;
            }
            else
            {
                remain = util.from_utf8(tail);
                if (remain.Length == 0)
                {
                    remain = null;
                }
            }
            pinned_sql.Free();
            return rc;
        }

        int ISQLite3Provider.sqlite3_db_status(IntPtr db, int op, out int current, out int highest, int resetFlg)
        {
            return NativeMethods.sqlite3_db_status(db, op, out current, out highest, resetFlg);
        }

        string ISQLite3Provider.sqlite3_sql(IntPtr stmt)
        {
            return util.from_utf8(NativeMethods.sqlite3_sql(stmt));
        }

        IntPtr ISQLite3Provider.sqlite3_db_handle(IntPtr stmt)
        {
            return NativeMethods.sqlite3_db_handle(stmt);
        }

        int ISQLite3Provider.sqlite3_blob_open(IntPtr db, string sdb, string table, string col, long rowid, int flags, out IntPtr blob)
        {
            return NativeMethods.sqlite3_blob_open(db, util.to_utf8(sdb), util.to_utf8(table), util.to_utf8(col), rowid, flags, out blob);
        }

        int ISQLite3Provider.sqlite3_blob_bytes(IntPtr blob)
        {
            return NativeMethods.sqlite3_blob_bytes(blob);
        }

        int ISQLite3Provider.sqlite3_blob_close(IntPtr blob)
        {
            return NativeMethods.sqlite3_blob_close(blob);
        }

        int ISQLite3Provider.sqlite3_blob_read(IntPtr blob, byte[] b, int n, int offset)
        {
            return NativeMethods.sqlite3_blob_read(blob, b, n, offset);
        }

        int ISQLite3Provider.sqlite3_blob_write(IntPtr blob, byte[] b, int n, int offset)
        {
            return NativeMethods.sqlite3_blob_write(blob, b, n, offset);
        }

        int ISQLite3Provider.sqlite3_blob_read(IntPtr blob, byte[] b, int bOffset, int n, int offset)
        {
            GCHandle pinned = GCHandle.Alloc(b, GCHandleType.Pinned);
            IntPtr ptr = pinned.AddrOfPinnedObject();
            int rc = NativeMethods.other_sqlite3_blob_read(blob, new IntPtr(ptr.ToInt64() + bOffset), n, offset);
            pinned.Free();
	    return rc;
        }

        int ISQLite3Provider.sqlite3_blob_write(IntPtr blob, byte[] b, int bOffset, int n, int offset)
        {
            GCHandle pinned = GCHandle.Alloc(b, GCHandleType.Pinned);
            IntPtr ptr = pinned.AddrOfPinnedObject();
            int rc = NativeMethods.other_sqlite3_blob_write(blob, new IntPtr(ptr.ToInt64() + bOffset), n, offset);
            pinned.Free();
	    return rc;
        }

        IntPtr ISQLite3Provider.sqlite3_backup_init(IntPtr destDb, string destName, IntPtr sourceDb, string sourceName)
        {
            return NativeMethods.sqlite3_backup_init(destDb, util.to_utf8(destName), sourceDb, util.to_utf8(sourceName));
        }

        int ISQLite3Provider.sqlite3_backup_step(IntPtr backup, int nPage)
        {
            return NativeMethods.sqlite3_backup_step(backup, nPage);
        }

        int ISQLite3Provider.sqlite3_backup_finish(IntPtr backup)
        {
            return NativeMethods.sqlite3_backup_finish(backup);
        }

        int ISQLite3Provider.sqlite3_backup_remaining(IntPtr backup)
        {
            return NativeMethods.sqlite3_backup_remaining(backup);
        }

        int ISQLite3Provider.sqlite3_backup_pagecount(IntPtr backup)
        {
            return NativeMethods.sqlite3_backup_pagecount(backup);
        }

        IntPtr ISQLite3Provider.sqlite3_next_stmt(IntPtr db, IntPtr stmt)
        {
            return NativeMethods.sqlite3_next_stmt(db, stmt);
        }

        long ISQLite3Provider.sqlite3_last_insert_rowid(IntPtr db)
        {
            return NativeMethods.sqlite3_last_insert_rowid(db);
        }

        int ISQLite3Provider.sqlite3_changes(IntPtr db)
        {
            return NativeMethods.sqlite3_changes(db);
        }

        int ISQLite3Provider.sqlite3_total_changes(IntPtr db)
        {
            return NativeMethods.sqlite3_total_changes(db);
        }

        int ISQLite3Provider.sqlite3_extended_result_codes(IntPtr db, int onoff)
        {
            return NativeMethods.sqlite3_extended_result_codes(db, onoff);
        }

        string ISQLite3Provider.sqlite3_errstr(int rc)
        {
            return util.from_utf8(NativeMethods.sqlite3_errstr(rc));
        }

        int ISQLite3Provider.sqlite3_errcode(IntPtr db)
        {
            return NativeMethods.sqlite3_errcode(db);
        }

        int ISQLite3Provider.sqlite3_extended_errcode(IntPtr db)
        {
            return NativeMethods.sqlite3_extended_errcode(db);
        }

        int ISQLite3Provider.sqlite3_busy_timeout(IntPtr db, int ms)
        {
            return NativeMethods.sqlite3_busy_timeout(db, ms);
        }

        int ISQLite3Provider.sqlite3_get_autocommit(IntPtr db)
        {
            return NativeMethods.sqlite3_get_autocommit(db);
        }

        int ISQLite3Provider.sqlite3_db_readonly(IntPtr db, string dbName)
        {
            return NativeMethods.sqlite3_db_readonly(db, util.to_utf8(dbName));
        }

        string ISQLite3Provider.sqlite3_db_filename(IntPtr db, string att)
	{
            return util.from_utf8(NativeMethods.sqlite3_db_filename(db, util.to_utf8(att)));
	}

        string ISQLite3Provider.sqlite3_errmsg(IntPtr db)
        {
            return util.from_utf8(NativeMethods.sqlite3_errmsg(db));
        }

        string ISQLite3Provider.sqlite3_libversion()
        {
            return util.from_utf8(NativeMethods.sqlite3_libversion());
        }

        int ISQLite3Provider.sqlite3_libversion_number()
        {
            return NativeMethods.sqlite3_libversion_number();
        }

        int ISQLite3Provider.sqlite3_threadsafe()
        {
            return NativeMethods.sqlite3_threadsafe();
        }

        int ISQLite3Provider.sqlite3_config(int op)
        {
            return NativeMethods.sqlite3_config_none(op);
        }

        int ISQLite3Provider.sqlite3_config(int op, int val)
        {
            return NativeMethods.sqlite3_config_int(op, val);
        }

        int ISQLite3Provider.sqlite3_initialize()
        {
            return NativeMethods.sqlite3_initialize();
        }

        int ISQLite3Provider.sqlite3_shutdown()
        {
            return NativeMethods.sqlite3_shutdown();
        }

        int ISQLite3Provider.sqlite3_enable_load_extension(IntPtr db, int onoff)
        {
            return NativeMethods.sqlite3_enable_load_extension(db, onoff);
        }

        // ----------------------------------------------------------------

        // Passing a callback into SQLite is tricky.  The implementation details
        // can vary depending on the .NET implementation, so we hide these
        // in platform-specific code underneath the ISQLite3Provider boundary.
        //
        // The caller gives us a delegate and an object they want passed to that
        // delegate.  We do not actually pass that stuff down to SQLite as
        // the callback.  Instead, we store the information and pass down a bridge
        // function, with an IntPtr that can be used to retrieve the info later.
        //
        // When SQLite calls the bridge function, we lookup the info we previously
        // stored and call the delegate provided by the upper layer.
        //
        // The class we use to remember the original info (delegate and user object)
        // is shared but not portable.  It is in the util.cs file which is compiled
        // into each platform assembly.

#if PLATFORM_IOS || PLATFORM_UNIFIED
        [MonoPInvokeCallback (typeof(NativeMethods.callback_commit))] // TODO not xplat
#endif
        static int commit_hook_bridge_impl(IntPtr p)
        {
            commit_hook_info hi = commit_hook_info.from_ptr(p);
            return hi.call();
        }

	NativeMethods.callback_commit commit_hook_bridge = new NativeMethods.callback_commit(commit_hook_bridge_impl);
        void ISQLite3Provider.sqlite3_commit_hook(IntPtr db, delegate_commit func, object v)
        {
		var info = hooks.getOrCreateFor(db);
            if (info.commit != null)
            {
                // TODO maybe turn off the hook here, for now
                info.commit.free();
                info.commit = null;
            }

            if (func != null)
            {
                info.commit = new commit_hook_info(func, v);
                NativeMethods.sqlite3_commit_hook(db, commit_hook_bridge, info.commit.ptr);
            }
            else
            {
                NativeMethods.sqlite3_commit_hook(db, null, IntPtr.Zero);
            }
        }

        // ----------------------------------------------------------------

        // Passing a callback into SQLite is tricky.  See comments near commit_hook
        // implementation in pinvoke/SQLite3Provider.cs

#if PLATFORM_IOS || PLATFORM_UNIFIED
        [MonoPInvokeCallback (typeof(NativeMethods.callback_scalar_function))] // TODO not xplat
#endif
        static void scalar_function_hook_bridge_impl(IntPtr context, int num_args, IntPtr argsptr)
        {
            IntPtr p = NativeMethods.sqlite3_user_data(context);
            scalar_function_hook_info hi = scalar_function_hook_info.from_ptr(p);
            hi.call(context, num_args, argsptr);
        }

	NativeMethods.callback_scalar_function scalar_function_hook_bridge = new NativeMethods.callback_scalar_function(scalar_function_hook_bridge_impl);
        int ISQLite3Provider.sqlite3_create_function(IntPtr db, string name, int nargs, object v, delegate_function_scalar func)
        {
        // the keys for this dictionary are nargs.name, not just the name
            string key = string.Format("{0}.{1}", nargs, name);
		var info = hooks.getOrCreateFor(db);
            if (info.scalar.ContainsKey(key))
            {
                scalar_function_hook_info hi = info.scalar[key];

                // TODO maybe turn off the hook here, for now
                hi.free();

                info.scalar.Remove(key);
            }

            // 1 is SQLITE_UTF8
            if (func != null)
            {
                scalar_function_hook_info hi = new scalar_function_hook_info(func, v);
                int rc = NativeMethods.sqlite3_create_function_v2(db, util.to_utf8(name), nargs, 1, hi.ptr, scalar_function_hook_bridge, null, null, null);
                if (rc == 0)
                {
                    info.scalar[key] = hi;
                }
                return rc;
            }
            else
            {
                return NativeMethods.sqlite3_create_function_v2(db, util.to_utf8(name), nargs, 1, IntPtr.Zero, null, null, null, null);
            }
        }

        // ----------------------------------------------------------------

#if PLATFORM_IOS || PLATFORM_UNIFIED
        [MonoPInvokeCallback (typeof(NativeMethods.callback_log))] // TODO not xplat
#endif
        static void log_hook_bridge_impl(IntPtr p, int rc, IntPtr s)
        {
            log_hook_info hi = log_hook_info.from_ptr(p);
            hi.call(rc, util.from_utf8(s));
        }

	NativeMethods.callback_log log_hook_bridge = new NativeMethods.callback_log(log_hook_bridge_impl);
        int ISQLite3Provider.sqlite3_config_log(delegate_log func, object v)
        {
            if (hooks.log != null)
            {
                // TODO maybe turn off the hook here, for now
                hooks.log.free();
                hooks.log = null;
            }

            if (func != null)
            {
                hooks.log = new log_hook_info(func, v);
                return NativeMethods.sqlite3_config_log(raw.SQLITE_CONFIG_LOG, log_hook_bridge, hooks.log.ptr);
            }
            else
            {
                return NativeMethods.sqlite3_config_log(raw.SQLITE_CONFIG_LOG, null, IntPtr.Zero);
            }
        }

        // ----------------------------------------------------------------

        // Passing a callback into SQLite is tricky.  See comments near commit_hook
        // implementation in pinvoke/SQLite3Provider.cs

#if PLATFORM_IOS || PLATFORM_UNIFIED
        [MonoPInvokeCallback (typeof(NativeMethods.callback_agg_function_step))] // TODO not xplat
#endif
        static void agg_function_hook_bridge_step_impl(IntPtr context, int num_args, IntPtr argsptr)
        {
            IntPtr agg = NativeMethods.sqlite3_aggregate_context(context, 8);
            // TODO error check agg nomem

            IntPtr p = NativeMethods.sqlite3_user_data(context);
            agg_function_hook_info hi = agg_function_hook_info.from_ptr(p);
            hi.call_step(context, agg, num_args, argsptr);
        }

#if PLATFORM_IOS || PLATFORM_UNIFIED
        [MonoPInvokeCallback (typeof(NativeMethods.callback_agg_function_final))] // TODO not xplat
#endif
        static void agg_function_hook_bridge_final_impl(IntPtr context)
        {
            IntPtr agg = NativeMethods.sqlite3_aggregate_context(context, 8);
            // TODO error check agg nomem

            IntPtr p = NativeMethods.sqlite3_user_data(context);
            agg_function_hook_info hi = agg_function_hook_info.from_ptr(p);
            hi.call_final(context, agg);
        }

	NativeMethods.callback_agg_function_step agg_function_hook_bridge_step = new NativeMethods.callback_agg_function_step(agg_function_hook_bridge_step_impl);
	NativeMethods.callback_agg_function_final agg_function_hook_bridge_final = new NativeMethods.callback_agg_function_final(agg_function_hook_bridge_final_impl);
        int ISQLite3Provider.sqlite3_create_function(IntPtr db, string name, int nargs, object v, delegate_function_aggregate_step func_step, delegate_function_aggregate_final func_final)
        {
        // the keys for this dictionary are nargs.name, not just the name
            string key = string.Format("{0}.{1}", nargs, name);
		var info = hooks.getOrCreateFor(db);
            if (info.agg.ContainsKey(key))
            {
                agg_function_hook_info hi = info.agg[key];

                // TODO maybe turn off the hook here, for now
                hi.free();

                info.agg.Remove(key);
            }

            // 1 is SQLITE_UTF8
            if (func_step != null)
            {
                // TODO both func_step and func_final must be non-null
                agg_function_hook_info hi = new agg_function_hook_info(func_step, func_final, v);
                int rc = NativeMethods.sqlite3_create_function_v2(db, util.to_utf8(name), nargs, 1, hi.ptr, null, agg_function_hook_bridge_step, agg_function_hook_bridge_final, null);
                if (rc == 0)
                {
                    info.agg[key] = hi;
                }
                return rc;
            }
            else
            {
                return NativeMethods.sqlite3_create_function_v2(db, util.to_utf8(name), nargs, 1, IntPtr.Zero, null, null, null, null);
            }
        }

        // ----------------------------------------------------------------

        // Passing a callback into SQLite is tricky.  See comments near commit_hook
        // implementation in pinvoke/SQLite3Provider.cs

#if PLATFORM_IOS || PLATFORM_UNIFIED
        [MonoPInvokeCallback (typeof(NativeMethods.callback_collation))] // TODO not xplat
#endif
        static int collation_hook_bridge_impl(IntPtr p, int len1, IntPtr pv1, int len2, IntPtr pv2)
        {
            collation_hook_info hi = collation_hook_info.from_ptr(p);
            return hi.call(util.from_utf8(pv1, len1), util.from_utf8(pv2, len2));
        }

	NativeMethods.callback_collation collation_hook_bridge = new NativeMethods.callback_collation(collation_hook_bridge_impl);
        int ISQLite3Provider.sqlite3_create_collation(IntPtr db, string name, object v, delegate_collation func)
        {
		var info = hooks.getOrCreateFor(db);
            if (info.collation.ContainsKey(name))
            {
                collation_hook_info hi = info.collation[name];

                // TODO maybe turn off the hook here, for now
                hi.free();

                info.collation.Remove(name);
            }

            // 1 is SQLITE_UTF8
            if (func != null)
            {
                collation_hook_info hi = new collation_hook_info(func, v);
                int rc = NativeMethods.sqlite3_create_collation(db, util.to_utf8(name), 1, hi.ptr, collation_hook_bridge);
                if (rc == 0)
                {
                    info.collation[name] = hi;
                }
                return rc;
            }
            else
            {
                return NativeMethods.sqlite3_create_collation(db, util.to_utf8(name), 1, IntPtr.Zero, null);
            }
        }

        // ----------------------------------------------------------------

        // Passing a callback into SQLite is tricky.  See comments near commit_hook
        // implementation in pinvoke/SQLite3Provider.cs

#if PLATFORM_IOS || PLATFORM_UNIFIED
        [MonoPInvokeCallback (typeof(NativeMethods.callback_update))] // TODO not xplat
#endif
        static void update_hook_bridge_impl(IntPtr p, int typ, IntPtr db, IntPtr tbl, Int64 rowid)
        {
            update_hook_info hi = update_hook_info.from_ptr(p);
            hi.call(typ, util.from_utf8(db), util.from_utf8(tbl), rowid);
        }

	NativeMethods.callback_update update_hook_bridge = new NativeMethods.callback_update(update_hook_bridge_impl);
        void ISQLite3Provider.sqlite3_update_hook(IntPtr db, delegate_update func, object v)
        {
		var info = hooks.getOrCreateFor(db);
            if (info.update != null)
            {
                // TODO maybe turn off the hook here, for now
                info.update.free();
                info.update = null;
            }

            if (func != null)
            {
                info.update = new update_hook_info(func, v);
                NativeMethods.sqlite3_update_hook(db, update_hook_bridge, info.update.ptr);
            }
            else
            {
                NativeMethods.sqlite3_update_hook(db, null, IntPtr.Zero);
            }
        }

        // ----------------------------------------------------------------

        // Passing a callback into SQLite is tricky.  See comments near commit_hook
        // implementation in pinvoke/SQLite3Provider.cs

#if PLATFORM_IOS || PLATFORM_UNIFIED
        [MonoPInvokeCallback (typeof(NativeMethods.callback_rollback))] // TODO not xplat
#endif
        static void rollback_hook_bridge_impl(IntPtr p)
        {
            rollback_hook_info hi = rollback_hook_info.from_ptr(p);
            hi.call();
        }

	NativeMethods.callback_rollback rollback_hook_bridge = new NativeMethods.callback_rollback(rollback_hook_bridge_impl);
        void ISQLite3Provider.sqlite3_rollback_hook(IntPtr db, delegate_rollback func, object v)
        {
		var info = hooks.getOrCreateFor(db);
            if (info.rollback != null)
            {
                // TODO maybe turn off the hook here, for now
                info.rollback.free();
                info.rollback = null;
            }

            if (func != null)
            {
                info.rollback = new rollback_hook_info(func, v);
                NativeMethods.sqlite3_rollback_hook(db, rollback_hook_bridge, info.rollback.ptr);
            }
            else
            {
                NativeMethods.sqlite3_rollback_hook(db, null, IntPtr.Zero);
            }
        }

        // ----------------------------------------------------------------

        // Passing a callback into SQLite is tricky.  See comments near commit_hook
        // implementation in pinvoke/SQLite3Provider.cs

#if PLATFORM_IOS || PLATFORM_UNIFIED
        [MonoPInvokeCallback (typeof(NativeMethods.callback_trace))] // TODO not xplat
#endif
        static void trace_hook_bridge_impl(IntPtr p, IntPtr s)
        {
            trace_hook_info hi = trace_hook_info.from_ptr(p);
            hi.call(util.from_utf8(s));
        }

	NativeMethods.callback_trace trace_hook_bridge = new NativeMethods.callback_trace(trace_hook_bridge_impl);
        void ISQLite3Provider.sqlite3_trace(IntPtr db, delegate_trace func, object v)
        {
		var info = hooks.getOrCreateFor(db);
            if (info.trace != null)
            {
                // TODO maybe turn off the hook here, for now
                info.trace.free();
                info.trace = null;
            }

            if (func != null)
            {
                info.trace = new trace_hook_info(func, v);
                NativeMethods.sqlite3_trace(db, trace_hook_bridge, info.trace.ptr);
            }
            else
            {
                NativeMethods.sqlite3_trace(db, null, IntPtr.Zero);
            }
        }

        // ----------------------------------------------------------------

        // Passing a callback into SQLite is tricky.  See comments near commit_hook
        // implementation in pinvoke/SQLite3Provider.cs

#if PLATFORM_IOS || PLATFORM_UNIFIED
        [MonoPInvokeCallback (typeof(NativeMethods.callback_profile))] // TODO not xplat
#endif
        static void profile_hook_bridge_impl(IntPtr p, IntPtr s, long elapsed)
        {
            profile_hook_info hi = profile_hook_info.from_ptr(p);
            hi.call(util.from_utf8(s), elapsed);
        }

	NativeMethods.callback_profile profile_hook_bridge = new NativeMethods.callback_profile(profile_hook_bridge_impl);
        void ISQLite3Provider.sqlite3_profile(IntPtr db, delegate_profile func, object v)
        {
		var info = hooks.getOrCreateFor(db);
            if (info.profile != null)
            {
                // TODO maybe turn off the hook here, for now
                info.profile.free();
                info.profile = null;
            }

            if (func != null)
            {
                info.profile = new profile_hook_info(func, v);
                NativeMethods.sqlite3_profile(db, profile_hook_bridge, info.profile.ptr);
            }
            else
            {
                NativeMethods.sqlite3_profile(db, null, IntPtr.Zero);
            }
        }

        // ----------------------------------------------------------------

        // Passing a callback into SQLite is tricky.  See comments near commit_hook
        // implementation in pinvoke/SQLite3Provider.cs

#if PLATFORM_IOS || PLATFORM_UNIFIED
        [MonoPInvokeCallback (typeof(NativeMethods.callback_progress_handler))] // TODO not xplat
#endif
        static int progress_handler_hook_bridge_impl(IntPtr p)
        {
            progress_handler_hook_info hi = progress_handler_hook_info.from_ptr(p);
            return hi.call();
        }

        NativeMethods.callback_progress_handler progress_handler_hook_bridge = new NativeMethods.callback_progress_handler(progress_handler_hook_bridge_impl);
        void ISQLite3Provider.sqlite3_progress_handler(IntPtr db, int instructions, delegate_progress_handler func, object v)
        {
		var info = hooks.getOrCreateFor(db);
            if (info.progress != null)
            {
                // TODO maybe turn off the hook here, for now
                info.progress.free();
                info.progress = null;
            }

            if (func != null)
            {
                info.progress = new progress_handler_hook_info(func, v);
                NativeMethods.sqlite3_progress_handler(db, instructions, progress_handler_hook_bridge, info.progress.ptr);
            }
            else
            {
                NativeMethods.sqlite3_progress_handler(db, instructions, null, IntPtr.Zero);
            }
        }

        // ----------------------------------------------------------------

        // ----------------------------------------------------------------

        // Passing a callback into SQLite is tricky.  See comments near commit_hook
        // implementation in pinvoke/SQLite3Provider.cs

#if PLATFORM_IOS || PLATFORM_UNIFIED
        [MonoPInvokeCallback (typeof(NativeMethods.callback_authorizer))] // TODO not xplat
#endif
        static int authorizer_hook_bridge_impl(IntPtr p, int action_code, IntPtr param0, IntPtr param1, IntPtr dbName, IntPtr inner_most_trigger_or_view)
        {
            authorizer_hook_info hi = authorizer_hook_info.from_ptr(p);
            return hi.call(action_code, util.from_utf8(param0), util.from_utf8(param1), util.from_utf8(dbName), util.from_utf8(inner_most_trigger_or_view));
        }

        NativeMethods.callback_authorizer authorizer_hook_bridge = new NativeMethods.callback_authorizer(authorizer_hook_bridge_impl);
        int ISQLite3Provider.sqlite3_set_authorizer(IntPtr db, delegate_authorizer func, object v)
        {
		var info = hooks.getOrCreateFor(db);
            if (info.authorizer != null)
            {
                // TODO maybe turn off the hook here, for now
                info.authorizer.free();
                info.authorizer = null;
            }

            if (func != null)
            {
                info.authorizer = new authorizer_hook_info(func, v);
                return NativeMethods.sqlite3_set_authorizer(db, authorizer_hook_bridge, info.authorizer.ptr);
            }
            else
            {
                return NativeMethods.sqlite3_set_authorizer(db, null, IntPtr.Zero);
            }
        }

        // ----------------------------------------------------------------

        long ISQLite3Provider.sqlite3_memory_used()
        {
            return NativeMethods.sqlite3_memory_used();
        }

        long ISQLite3Provider.sqlite3_memory_highwater(int resetFlag)
        {
            return NativeMethods.sqlite3_memory_highwater(resetFlag);
        }

        int ISQLite3Provider.sqlite3_status(int op, out int current, out int highwater, int resetFlag)
        {
            return NativeMethods.sqlite3_status(op, out current, out highwater, resetFlag);
        }

        string ISQLite3Provider.sqlite3_sourceid()
        {
            return util.from_utf8(NativeMethods.sqlite3_sourceid());
        }

        void ISQLite3Provider.sqlite3_result_int64(IntPtr ctx, long val)
        {
            NativeMethods.sqlite3_result_int64(ctx, val);
        }

        void ISQLite3Provider.sqlite3_result_int(IntPtr ctx, int val)
        {
            NativeMethods.sqlite3_result_int(ctx, val);
        }

        void ISQLite3Provider.sqlite3_result_double(IntPtr ctx, double val)
        {
            NativeMethods.sqlite3_result_double(ctx, val);
        }

        void ISQLite3Provider.sqlite3_result_null(IntPtr stm)
        {
            NativeMethods.sqlite3_result_null(stm);
        }

        void ISQLite3Provider.sqlite3_result_error(IntPtr ctx, string val)
        {
            NativeMethods.sqlite3_result_error(ctx, util.to_utf8(val), -1);
        }

        void ISQLite3Provider.sqlite3_result_text(IntPtr ctx, string val)
        {
            NativeMethods.sqlite3_result_text(ctx, util.to_utf8(val), -1, new IntPtr(-1));
        }

        void ISQLite3Provider.sqlite3_result_blob(IntPtr ctx, byte[] blob)
        {
            NativeMethods.sqlite3_result_blob(ctx, blob, blob.Length, new IntPtr(-1));
        }

        void ISQLite3Provider.sqlite3_result_zeroblob(IntPtr ctx, int n)
        {
            NativeMethods.sqlite3_result_zeroblob(ctx, n);
        }

        // TODO sqlite3_result_value

        void ISQLite3Provider.sqlite3_result_error_toobig(IntPtr ctx)
        {
            NativeMethods.sqlite3_result_error_toobig(ctx);
        }

        void ISQLite3Provider.sqlite3_result_error_nomem(IntPtr ctx)
        {
            NativeMethods.sqlite3_result_error_nomem(ctx);
        }

        void ISQLite3Provider.sqlite3_result_error_code(IntPtr ctx, int code)
        {
            NativeMethods.sqlite3_result_error_code(ctx, code);
        }

        byte[] ISQLite3Provider.sqlite3_value_blob(IntPtr p)
        {
            IntPtr blobPointer = NativeMethods.sqlite3_value_blob(p);
            if (blobPointer == IntPtr.Zero)
            {
                return null;
            }

            var length = NativeMethods.sqlite3_value_bytes(p);
            byte[] result = new byte[length];
            Marshal.Copy(blobPointer, (byte[])result, 0, length);
            return result;
        }

        int ISQLite3Provider.sqlite3_value_bytes(IntPtr p)
        {
            return NativeMethods.sqlite3_value_bytes(p);
        }

        double ISQLite3Provider.sqlite3_value_double(IntPtr p)
        {
            return NativeMethods.sqlite3_value_double(p);
        }

        int ISQLite3Provider.sqlite3_value_int(IntPtr p)
        {
            return NativeMethods.sqlite3_value_int(p);
        }

        long ISQLite3Provider.sqlite3_value_int64(IntPtr p)
        {
            return NativeMethods.sqlite3_value_int64(p);
        }

        int ISQLite3Provider.sqlite3_value_type(IntPtr p)
        {
            return NativeMethods.sqlite3_value_type(p);
        }

        string ISQLite3Provider.sqlite3_value_text(IntPtr p)
        {
            return util.from_utf8(NativeMethods.sqlite3_value_text(p));
        }

        int ISQLite3Provider.sqlite3_bind_int(IntPtr stm, int paramIndex, int val)
        {
            return NativeMethods.sqlite3_bind_int(stm, paramIndex, val);
        }

        int ISQLite3Provider.sqlite3_bind_int64(IntPtr stm, int paramIndex, long val)
        {
            return NativeMethods.sqlite3_bind_int64(stm, paramIndex, val);
        }

        int ISQLite3Provider.sqlite3_bind_text(IntPtr stm, int paramIndex, string t)
        {
            return NativeMethods.sqlite3_bind_text(stm, paramIndex, util.to_utf8(t), -1, new IntPtr(-1));
        }

        int ISQLite3Provider.sqlite3_bind_double(IntPtr stm, int paramIndex, double val)
        {
            return NativeMethods.sqlite3_bind_double(stm, paramIndex, val);
        }

        int ISQLite3Provider.sqlite3_bind_blob(IntPtr stm, int paramIndex, byte[] blob)
        {
            return NativeMethods.sqlite3_bind_blob(stm, paramIndex, blob, blob.Length, new IntPtr(-1));
        }

        int ISQLite3Provider.sqlite3_bind_zeroblob(IntPtr stm, int paramIndex, int size)
        {
            return NativeMethods.sqlite3_bind_zeroblob(stm, paramIndex, size);
        }

        int ISQLite3Provider.sqlite3_bind_null(IntPtr stm, int paramIndex)
        {
            return NativeMethods.sqlite3_bind_null(stm, paramIndex);
        }

        int ISQLite3Provider.sqlite3_bind_parameter_count(IntPtr stm)
        {
            return NativeMethods.sqlite3_bind_parameter_count(stm);
        }

        string ISQLite3Provider.sqlite3_bind_parameter_name(IntPtr stm, int paramIndex)
        {
            return util.from_utf8(NativeMethods.sqlite3_bind_parameter_name(stm, paramIndex));
        }

        int ISQLite3Provider.sqlite3_bind_parameter_index(IntPtr stm, string paramName)
        {
            return NativeMethods.sqlite3_bind_parameter_index(stm, util.to_utf8(paramName));
        }

        int ISQLite3Provider.sqlite3_step(IntPtr stm)
        {
            return NativeMethods.sqlite3_step(stm);
        }

        int ISQLite3Provider.sqlite3_stmt_busy(IntPtr stm)
        {
            return NativeMethods.sqlite3_stmt_busy(stm);
        }

        int ISQLite3Provider.sqlite3_stmt_readonly(IntPtr stm)
        {
            return NativeMethods.sqlite3_stmt_readonly(stm);
        }

        int ISQLite3Provider.sqlite3_column_int(IntPtr stm, int columnIndex)
        {
            return NativeMethods.sqlite3_column_int(stm, columnIndex);
        }

        long ISQLite3Provider.sqlite3_column_int64(IntPtr stm, int columnIndex)
        {
            return NativeMethods.sqlite3_column_int64(stm, columnIndex);
        }

        string ISQLite3Provider.sqlite3_column_text(IntPtr stm, int columnIndex)
        {
            return util.from_utf8(NativeMethods.sqlite3_column_text(stm, columnIndex));
        }

        string ISQLite3Provider.sqlite3_column_decltype(IntPtr stm, int columnIndex)
        {
            return util.from_utf8(NativeMethods.sqlite3_column_decltype(stm, columnIndex));
        }

        double ISQLite3Provider.sqlite3_column_double(IntPtr stm, int columnIndex)
        {
            return NativeMethods.sqlite3_column_double(stm, columnIndex);
        }

        byte[] ISQLite3Provider.sqlite3_column_blob(IntPtr stm, int columnIndex)
        {
            IntPtr blobPointer = NativeMethods.sqlite3_column_blob(stm, columnIndex);
            if (blobPointer == IntPtr.Zero)
            {
                return null;
            }

            var length = NativeMethods.sqlite3_column_bytes(stm, columnIndex);
            byte[] result = new byte[length];
            Marshal.Copy(blobPointer, (byte[])result, 0, length);
            return result;
        }

        int ISQLite3Provider.sqlite3_column_type(IntPtr stm, int columnIndex)
        {
            return NativeMethods.sqlite3_column_type(stm, columnIndex);
        }

        int ISQLite3Provider.sqlite3_column_bytes(IntPtr stm, int columnIndex)
        {
            return NativeMethods.sqlite3_column_bytes(stm, columnIndex);
        }

        int ISQLite3Provider.sqlite3_column_count(IntPtr stm)
        {
            return NativeMethods.sqlite3_column_count(stm);
        }

        int ISQLite3Provider.sqlite3_data_count(IntPtr stm)
        {
            return NativeMethods.sqlite3_data_count(stm);
        }

        string ISQLite3Provider.sqlite3_column_name(IntPtr stm, int columnIndex)
        {
            return util.from_utf8(NativeMethods.sqlite3_column_name(stm, columnIndex));
        }

        string ISQLite3Provider.sqlite3_column_origin_name(IntPtr stm, int columnIndex)
        {
            return util.from_utf8(NativeMethods.sqlite3_column_origin_name(stm, columnIndex));
        }

        string ISQLite3Provider.sqlite3_column_table_name(IntPtr stm, int columnIndex)
        {
            return util.from_utf8(NativeMethods.sqlite3_column_table_name(stm, columnIndex));
        }

        string ISQLite3Provider.sqlite3_column_database_name(IntPtr stm, int columnIndex)
        {
            return util.from_utf8(NativeMethods.sqlite3_column_database_name(stm, columnIndex));
        }

        int ISQLite3Provider.sqlite3_reset(IntPtr stm)
        {
            return NativeMethods.sqlite3_reset(stm);
        }

        int ISQLite3Provider.sqlite3_clear_bindings(IntPtr stm)
        {
            return NativeMethods.sqlite3_clear_bindings(stm);
        }

        int ISQLite3Provider.sqlite3_stmt_status(IntPtr stm, int op, int resetFlg)
        {
            return NativeMethods.sqlite3_stmt_status(stm, op, resetFlg);
        }

        int ISQLite3Provider.sqlite3_finalize(IntPtr stm)
        {
            return NativeMethods.sqlite3_finalize(stm);
        }

        int ISQLite3Provider.sqlite3_wal_autocheckpoint(IntPtr db, int n)
        {
            return NativeMethods.sqlite3_wal_autocheckpoint(db, n);
        }

        int ISQLite3Provider.sqlite3_wal_checkpoint(IntPtr db, string dbName)
        {
            return NativeMethods.sqlite3_wal_checkpoint(db, util.to_utf8(dbName));
        }

        int ISQLite3Provider.sqlite3_wal_checkpoint_v2(IntPtr db, string dbName, int eMode, out int logSize, out int framesCheckPointed)
        {
            return NativeMethods.sqlite3_wal_checkpoint_v2(db, util.to_utf8(dbName), eMode, out logSize, out framesCheckPointed);
        }

        private static class NativeMethods
        {
        private const string SQLITE_DLL = "REPLACE_WITH_ACTUAL_DLL_NAME";

#if PRELOAD_FROM_ARCH_DIRECTORY
	// TODO on which Windows platforms is LoadLibraryEx available?

        [DllImport("kernel32")]
        private static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags);

        // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
        // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
        // https://github.com/aspnet/DataCommon.SQLite/blob/dev/src/Microsoft.Data.SQLite/Utilities/NativeLibraryLoader.cs

        private static bool TryLoadFromArchDirectory()
        {
	    var dllName = string.Format("{0}.dll", SQLITE_DLL);

		string baseDirectory = new Uri(AppDomain.CurrentDomain.BaseDirectory).LocalPath;
		if (baseDirectory == null)
		{
#if OLD_REFLECTION
			var currentAssembly = typeof(NativeMethods).Assembly;
#else
			var currentAssembly = typeof(NativeMethods).GetTypeInfo().Assembly;
#endif
			var codeBase = currentAssembly.CodeBase;
			var uri = new UriBuilder(codeBase);
			baseDirectory = System.IO.Path.GetDirectoryName(Uri.UnescapeDataString(uri.Path));

		}
		if (baseDirectory == null)
		{
			return false;
		}
            System.Diagnostics.Debug.Assert(System.IO.Path.IsPathRooted(baseDirectory), "baseDirectory is not rooted.");

            var architecture = IntPtr.Size == 4
                ? "x86"
                : "x64";

            var dllPath = System.IO.Path.Combine(System.IO.Path.Combine(baseDirectory, architecture), dllName);
            if (!System.IO.File.Exists(dllPath))
	    {
                return false;
	    }

	    const uint LOAD_WITH_ALTERED_SEARCH_PATH = 8;

            var ptr = LoadLibraryEx(dllPath, IntPtr.Zero, LOAD_WITH_ALTERED_SEARCH_PATH);
            return ptr != IntPtr.Zero;
        }
#endif

        static NativeMethods()
        {
#if PRELOAD_FROM_ARCH_DIRECTORY
	    // TODO the check below is intended to prevent the LoadLibraryEx call
	    // from happening when using the net45 build on Mono on non-Windows
	    // platforms.  this approach is almost certainly wrong-ish for .NET Core.
	    if (
		(System.Environment.OSVersion.Platform == System.PlatformID.Win32NT)
		&& (TryLoadFromArchDirectory())
	       )
	    {
		return;
	    }
#endif

        }

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern void sqlite3_activate_cerod(byte[] passPhrase);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern void sqlite3_activate_see(byte[] passPhrase);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_close(IntPtr db);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_close_v2(IntPtr db); /* 3.7.14+ */

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_enable_shared_cache(int enable);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern void sqlite3_interrupt(IntPtr db);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_finalize(IntPtr stmt);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_reset(IntPtr stmt);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_clear_bindings(IntPtr stmt);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_stmt_status(IntPtr stm, int op, int resetFlg);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_bind_parameter_name(IntPtr stmt, int index);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_column_database_name(IntPtr stmt, int index);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_column_database_name16(IntPtr stmt, int index);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_column_decltype(IntPtr stmt, int index);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_column_decltype16(IntPtr stmt, int index);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_column_name(IntPtr stmt, int index);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_column_name16(IntPtr stmt, int index);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_column_origin_name(IntPtr stmt, int index);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_column_origin_name16(IntPtr stmt, int index);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_column_table_name(IntPtr stmt, int index);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_column_table_name16(IntPtr stmt, int index);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_column_text(IntPtr stmt, int index);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_column_text16(IntPtr stmt, int index);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_errmsg(IntPtr db);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_db_readonly(IntPtr db, byte[] dbName);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_db_filename(IntPtr db, byte[] att);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_prepare(IntPtr db, IntPtr pSql, int nBytes, out IntPtr stmt, out IntPtr ptrRemain);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_prepare_v2(IntPtr db, IntPtr pSql, int nBytes, out IntPtr stmt, out IntPtr ptrRemain);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_db_status(IntPtr db, int op, out int current, out int highest, int resetFlg);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_complete(byte[] pSql);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_compileoption_used(byte[] pSql);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_compileoption_get(int n);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_table_column_metadata(IntPtr db, byte[] dbName, byte[] tblName, byte[] colName, out IntPtr ptrDataType, out IntPtr ptrCollSeq, out int notNull, out int primaryKey, out int autoInc);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_value_text(IntPtr p);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_value_text16(IntPtr p);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_enable_load_extension(
            IntPtr db, int enable);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_load_extension(
            IntPtr db, byte[] fileName, byte[] procName, ref IntPtr pError);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_initialize();

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_shutdown();

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_libversion();

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_libversion_number();

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_threadsafe();

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_sourceid();

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_malloc(int n);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_realloc(IntPtr p, int n);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern void sqlite3_free(IntPtr p);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_open(byte[] filename, out IntPtr db);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_open_v2(byte[] filename, out IntPtr db, int flags, byte[] vfs);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_vfs_find(byte[] vfs);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
            public static extern int sqlite3_open16(string fileName, out IntPtr db);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern long sqlite3_last_insert_rowid(IntPtr db);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_changes(IntPtr db);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_total_changes(IntPtr db);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern long sqlite3_memory_used();

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern long sqlite3_memory_highwater(int resetFlag);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_status(int op, out int current, out int highwater, int resetFlag);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_busy_timeout(IntPtr db, int ms);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_bind_blob(IntPtr stmt, int index, byte[] val, int nSize, IntPtr nTransient);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_bind_zeroblob(IntPtr stmt, int index, int size);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_bind_double(IntPtr stmt, int index, double val);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_bind_int(IntPtr stmt, int index, int val);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_bind_int64(IntPtr stmt, int index, long val);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_bind_null(IntPtr stmt, int index);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_bind_text(IntPtr stmt, int index, byte[] val, int nlen, IntPtr pvReserved);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_bind_parameter_count(IntPtr stmt);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_bind_parameter_index(IntPtr stmt, byte[] strName);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_column_count(IntPtr stmt);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_data_count(IntPtr stmt);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_step(IntPtr stmt);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_sql(IntPtr stmt);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern double sqlite3_column_double(IntPtr stmt, int index);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_column_int(IntPtr stmt, int index);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern long sqlite3_column_int64(IntPtr stmt, int index);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_column_blob(IntPtr stmt, int index);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_column_bytes(IntPtr stmt, int index);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_column_type(IntPtr stmt, int index);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_aggregate_count(IntPtr context);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_value_blob(IntPtr p);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_value_bytes(IntPtr p);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern double sqlite3_value_double(IntPtr p);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_value_int(IntPtr p);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern long sqlite3_value_int64(IntPtr p);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_value_type(IntPtr p);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_user_data(IntPtr context);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern void sqlite3_result_blob(IntPtr context, byte[] val, int nSize, IntPtr pvReserved);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern void sqlite3_result_double(IntPtr context, double val);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern void sqlite3_result_error(IntPtr context, byte[] strErr, int nLen);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern void sqlite3_result_int(IntPtr context, int val);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern void sqlite3_result_int64(IntPtr context, long val);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern void sqlite3_result_null(IntPtr context);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern void sqlite3_result_text(IntPtr context, byte[] val, int nLen, IntPtr pvReserved);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern void sqlite3_result_zeroblob(IntPtr context, int n);

            // TODO sqlite3_result_value

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern void sqlite3_result_error_toobig(IntPtr context);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern void sqlite3_result_error_nomem(IntPtr context);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern void sqlite3_result_error_code(IntPtr context, int code);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_aggregate_context(IntPtr context, int nBytes);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
            public static extern int sqlite3_bind_text16(IntPtr stmt, int index, string val, int nlen, IntPtr pvReserved);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
            public static extern void sqlite3_result_error16(IntPtr context, string strName, int nLen);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
            public static extern void sqlite3_result_text16(IntPtr context, string strName, int nLen, IntPtr pvReserved);

#if not // TODO removed, perhaps temporarily.  not sure if we want these or PRAGMA key.
            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_key(IntPtr db, byte[] key, int keylen);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_rekey(IntPtr db, byte[] key, int keylen);
#endif

            // Since sqlite3_config() takes a variable argument list, we have to overload declarations
            // for all possible calls that we want to use.
            [DllImport(SQLITE_DLL, ExactSpelling=true, EntryPoint = "sqlite3_config", CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_config_none(int op);

            [DllImport(SQLITE_DLL, ExactSpelling=true, EntryPoint = "sqlite3_config", CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_config_int(int op, int val);

            [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
            public delegate void callback_log(IntPtr pUserData, int errorCode, IntPtr pMessage);

            [DllImport(SQLITE_DLL, ExactSpelling=true, EntryPoint = "sqlite3_config", CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_config_log(int op, callback_log func, IntPtr pvUser);

            [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
            public delegate void callback_agg_function_final(IntPtr context);

            [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
            public delegate void callback_scalar_function(IntPtr context, int nArgs, IntPtr argsptr);

            [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
            public delegate void callback_agg_function_step(IntPtr context, int nArgs, IntPtr argsptr);

            [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
            public delegate void callback_destroy(IntPtr p);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_create_function_v2(IntPtr db, byte[] strName, int nArgs, int nType, IntPtr pvUser, callback_scalar_function func, callback_agg_function_step fstep, callback_agg_function_final ffinal, callback_destroy fdestroy);

            [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
            public delegate int callback_collation(IntPtr puser, int len1, IntPtr pv1, int len2, IntPtr pv2);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_create_collation(IntPtr db, byte[] strName, int nType, IntPtr pvUser, callback_collation func);

            [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
            public delegate void callback_update(IntPtr p, int typ, IntPtr db, IntPtr tbl, long rowid);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_update_hook(IntPtr db, callback_update func, IntPtr pvUser);

            [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
            public delegate int callback_commit(IntPtr puser);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_commit_hook(IntPtr db, callback_commit func, IntPtr pvUser);

            [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
            public delegate void callback_profile(IntPtr puser, IntPtr statement, long elapsed);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_profile(IntPtr db, callback_profile func, IntPtr pvUser);

            [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
            public delegate int callback_progress_handler(IntPtr puser);

            [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
            public delegate int callback_authorizer(IntPtr puser, int action_code, IntPtr param0, IntPtr param1, IntPtr dbName, IntPtr inner_most_trigger_or_view);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_progress_handler(IntPtr db, int instructions, callback_progress_handler func, IntPtr pvUser);

            [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
            public delegate void callback_trace(IntPtr puser, IntPtr statement);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_trace(IntPtr db, callback_trace func, IntPtr pvUser);

            [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
            public delegate void callback_rollback(IntPtr puser);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_rollback_hook(IntPtr db, callback_rollback func, IntPtr pvUser);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_db_handle(IntPtr stmt);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_next_stmt(IntPtr db, IntPtr stmt);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_stmt_busy(IntPtr stmt);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_stmt_readonly(IntPtr stmt);

            [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
            public delegate int callback_exec(IntPtr db, int n, IntPtr values, IntPtr names);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_exec(IntPtr db, byte[] strSql, callback_exec cb, IntPtr pvParam, out IntPtr errMsg);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_get_autocommit(IntPtr db);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_extended_result_codes(IntPtr db, int onoff);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_errcode(IntPtr db);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_extended_errcode(IntPtr db);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_errstr(int rc); /* 3.7.15+ */

            // Since sqlite3_log() takes a variable argument list, we have to overload declarations
            // for all possible calls.  For now, we are only exposing a single string, and
            // depend on the caller to format the string.
            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern void sqlite3_log(int iErrCode, byte[] zFormat);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_file_control(IntPtr db, byte[] zDbName, int op, IntPtr pArg);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr sqlite3_backup_init(IntPtr destDb, byte[] zDestName, IntPtr sourceDb, byte[] zSourceName);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_backup_step(IntPtr backup, int nPage);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_backup_finish(IntPtr backup);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_backup_remaining(IntPtr backup);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_backup_pagecount(IntPtr backup);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_blob_open(IntPtr db, byte[] sdb, byte[] table, byte[] col, long rowid, int flags, out IntPtr blob);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_blob_write(IntPtr blob, byte[] b, int n, int offset);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_blob_read(IntPtr blob, byte[] b, int n, int offset);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl, EntryPoint="sqlite3_blob_write")]
            public static extern int other_sqlite3_blob_write(IntPtr blob, IntPtr b, int n, int offset);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl, EntryPoint="sqlite3_blob_read")]
            public static extern int other_sqlite3_blob_read(IntPtr blob, IntPtr b, int n, int offset);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_blob_bytes(IntPtr blob);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_blob_close(IntPtr blob);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_wal_autocheckpoint(IntPtr db, int n);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_wal_checkpoint(IntPtr db, byte[] dbName);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_wal_checkpoint_v2(IntPtr db, byte[] dbName, int eMode, out int logSize, out int framesCheckPointed);

            [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CallingConvention.Cdecl)]
            public static extern int sqlite3_set_authorizer(IntPtr db, callback_authorizer cb, IntPtr pvUser);
#if NETFX_CORE
            [DllImport(SQLITE_DLL, ExactSpelling=true, EntryPoint = "sqlite3_win32_set_directory", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Unicode)]
            public static extern int sqlite3_win32_set_directory (uint directoryType, string directoryPath);
#endif

        }
    }
}


text:
#ifndef NODE_LLVM_MODULE_H
#define NODE_LLVM_MODULE_H

#include "node-llvm.h"

namespace jsllvm {

  class Module : public node::ObjectWrap {
  public:
    static void Init(v8::Handle<v8::Object> target);

    static v8::Handle<v8::Value> New(::llvm::Module *llvm_module);

    static llvm::Module* GetLLVMObj (v8::Local<v8::Value> value) {
      if (value->IsNull())
	return NULL;
      return node::ObjectWrap::Unwrap<Module>(value->ToObject())->llvm_module;
    }

  private:
    ::llvm::Module *llvm_module;

    Module(::llvm::Module *llvm_module);
    Module();
    virtual ~Module();

    static v8::Handle<v8::Value> New(const v8::Arguments& args);
    static v8::Handle<v8::Value> GetGlobalVariable (const v8::Arguments& args);
    static v8::Handle<v8::Value> GetOrInsertIntrinsic (const v8::Arguments& args);
    static v8::Handle<v8::Value> GetOrInsertFunction (const v8::Arguments& args);
    static v8::Handle<v8::Value> GetOrInsertGlobal (const v8::Arguments& args);
    static v8::Handle<v8::Value> GetOrInsertExternalFunction (const v8::Arguments& args);
    static v8::Handle<v8::Value> GetFunction (const v8::Arguments& args);
    static v8::Handle<v8::Value> Dump (const v8::Arguments& args);
    static v8::Handle<v8::Value> ToString (const v8::Arguments& args);
    static v8::Handle<v8::Value> WriteToFile (const v8::Arguments& args);
    static v8::Handle<v8::Value> WriteBitcodeToFile (const v8::Arguments& args);

    static v8::Handle<v8::Value> AddModuleFlag (const v8::Arguments& args);

    static v8::Handle<v8::Value> SetDataLayout (const v8::Arguments& args);
    static v8::Handle<v8::Value> SetTriple (const v8::Arguments& args);

    static v8::Persistent<v8::FunctionTemplate> s_ct;
    static v8::Persistent<v8::Function> s_func;
  };
};

#endif /* NODE_LLVM_MODULE_H */

redpajama_set_name: RedPajamaGithub


text:
@interface MMRefreshView : UIView
+(instancetype)refreshViewWithScrollView:(UIScrollView *)scrollview;

- (void)endRefresh;
@end


text:
<?php

/**
 * Return element of List by index at key
 *
 * @author Ivan Shumkov
 * @package Rediska
 * @subpackage Commands
 * @version @package_version@
 * @link http://rediska.geometria-lab.net
 * @license http://www.opensource.org/licenses/bsd-license.php
 */
class Rediska_Command_GetFromList extends Rediska_Command_Abstract
{
    /**
     * Create command
     *
     * @param string  $key   Key name
     * @param integer $index Index
     * @return Rediska_Connection_Exec
     */
    public function create($key, $index)
    {
        $connection = $this->_rediska->getConnectionByKeyName($key);

        $command = array('LINDEX',
                         $this->_rediska->getOption('namespace') . $key,
                         $index);

        return new Rediska_Connection_Exec($connection, $command);
    }

    /**
     * Parse response
     *
     * @param string $response
     * @return mixed
     */
    public function parseResponse($response)
    {
        return $this->_rediska->getSerializer()->unserialize($response);
    }
}


text:
define(function(require){

    getScriptProvider.$inject = ['$q'];
    function getScriptProvider($q){

        // @TODO: separate the parsing into a different module (make this a dependency)
        function getScript(url, options){
            options || (options = {});
            var def = $q.defer(), target = '';

            // if url doesn't starts with / or has : then add baseUrl
            /^\/|:/.test(url) || (target += options.baseUrl ? options.baseUrl + '/' : '');

            target += url;

            options.isText && (target = 'text!' + target);
            options.bustCache && (target += '?bust=' + (new Date()).getTime());

            require([target], function(script){
                def.resolve(script);
            }, function(err){
                def.reject(err);
            });

            return def.promise;
        }

        return getScript;
    }

    return getScriptProvider;

});


text:
from geom4d import *
from geom4d.point import Point


text:
alias gl='git pull --prune'
alias glog="git log --graph --pretty=format:'%Cred%h%Creset %an: %s - %Creset %C(yellow)%d%Creset %Cgreen(%cr)%Creset' --abbrev-commit --date=relative"
alias gp='git push -u origin HEAD'
alias gd='git diff'
alias gds='git diff --cached'
alias gc='git commit -v'
alias gca='git commit -a'
alias gco='git checkout'
alias gb='git branch'
alias gs='git status -sb' # upgrade your git if -sb breaks for you. it's fun.
alias grm="git status | grep deleted | awk '{print \$3}' | xargs git rm"
alias g="git"
alias ga="git add"
alias gpr="git pull --rebase"
# only does it on master
alias gbranchprune='git branch --merged | grep -v "\*" | xargs -n 1 git branch -d'


text:
# 前言
好几个月之前关于Android App热补丁修复火了一把,源于QQ空间团队的一篇文章[安卓App热补丁动态修复技术介绍](http://zhuanlan.zhihu.com/magilu/20308548),然后各大厂的开源项目都出来了,本文的实践基于[HotFix](https://github.com/dodola/HotFix),也就是QQ空间技术团队那篇文章所应用的技术,笔者会把整个过程的细节和思路在文章中详说,研究这个的出发点也是为了能紧急修复app的bug,而不需要重复发包,不需要用户重新下载app就能把问题解决,个人觉得这个还是蛮有价值的,虽然老板不知道....。

# 项目结构

![项目结构](http://img.blog.csdn.net/20160309152937798)

这里笔者创建一个新的项目"HotFixDemo",带大家一步一步来完成Hotfix这个框架实现,这个项目包含以下module:
- app :我们的Android应用程序Module。
- buildsrc :使用Groovy实现的项目,提供了一个类,用来实现修改class文件的操作。
- hackdex :提供了一个类,后面会用来打包成hack.dex,也是buildsrc里面实现在所有类的构造函数插入的一段代码所引用到的类。
- hotfixlib :这个module最终会被app关联,里面提供实现热补丁的核心方法

这个Demo里面的代码跟HotFix框架基本无异,主要是告诉大家它实现的过程,如果光看代码,不实践是无法把它应用到你自己的app上去的,因为有很多比较深入的知识需要你去理解。

# 先说原理
关于实现原理,QQ空间那篇文章已经说过了,这里我再重新阐述一遍:
- Android使用的是PathClassLoader作为其类的加载器
- 一个ClassLoader可以包含多个dex文件,每个dex文件是一个Element,多个dex排列成一个有序的**dexElements**数组
- 当找类的时候会遍历dexElements数组,从dex文件中找类,找到则返回,否则继续下一个dex文件查找
- 热补丁的方案,其实就是将有问题的类单独打包成一个dex文件(如:patch.dex),然后将这个dex插入到dexElements数组的最前面去。

ok,这个就是HotFix对app进行热补丁的原理,**其实就是用ClassLoader加载机制,覆盖掉有问题的方法,然后我们所谓的补丁就是将有问题的类打成一个包**。

# 再说问题
当然要实现热补丁动态修复不会很容易,我们首要解决的一个问题是:
>**当虚拟机启动时,当verify选项被打开时,如果static方法、private方法、构造函数等,其中的直接引用(第一层关系)到的类都在同一个dex文件中,那么该类会被打上CLASS_ISPREERIFIED标记**

如下图所示:
![CLASS_ISPREERIFIED](http://img.blog.csdn.net/20160309161102236)

如果一个类被打上了CLASS_ISPREERIFIED这个标志,如果该类引用的另外一个类在另一个dex文件,就会报错。简单来说,就是你在打补丁之前,你所修复的类已经被打上标记,你通过补丁去修复bug的时候这个时候你就不能完成校验,就会报错。

# 解决问题
要解决上一节所提到的问题就要在apk打包之前就阻止相关类打上CLASS_ISPREERIFIED标志,解决方案如下:
 在所有类的构造函数插入一段代码,如:

```
public class BugClass {
    public BugClass() {
        System.out.println(AntilazyLoad.class);
    }

    public String bug() {
        return "bug class";
    }
}

```

> 其中引用到的AntilazyLoad这个类会单独打包成hack.dex,这样当安装apk的时候,classes.dex内的类都会引用一个不相同的dex中的AntilazyLoad类,这样就解决CLASS_ISPREERIFIED标记问题了。

# 实现细节
上面几节讲完原理、之后抛出了问题,再提出解决方案,相信大家对整个热补丁修复框架有了一定的认识,至少我们知道它到底是怎么一回事。下面来讲实现细节:

## 创建两个类

```
package com.devilwwj.hotfixdemo;

/**
 * com.devilwwj.hotfixdemo
 * Created by devilwwj on 16/3/8.
 */
public class BugClass {

    public String bug() {
        return "bug class";
    }
}
```

```
package com.devilwwj.hotfixdemo;

/**
 * com.devilwwj.hotfixdemo
 * Created by devilwwj on 16/3/8.
 */
public class LoadBugClass {
    public String getBugString() {
        BugClass bugClass = new BugClass();
        return bugClass.bug();
    }
}
```

我们需要做的是在这两个类的class文件的构造方法中插入一段代码:

```
System.out.println(AntilazyLoad.class);
```

## 创建hackdex模块并创建AntilazyLoad类

看图就好了:

![hackdex模块](http://img.blog.csdn.net/20160309164412186)

## 将AntilazyLoad单独打成hack_dex.jar包

通过以下命令来实现:

```
jar cvf hack.jar com.devilwwj.hackdex/*
```
这个命令会将AntilazyLoad类打包成hack.jar文件

```
dx --dex --output hack_dex.jar hack.jar
```
这个命令使用dx工具对hack.jar进行转化,生成hack_dex.jar文件

dx工具在我们的sdk/build-tools下
![dx工具](http://img.blog.csdn.net/20160309165327073)

最终我们把hack_dex.jar文件放到项目的assets目录下:

![hack_dex.jar](http://img.blog.csdn.net/20160309165550425)

## 使用javassist实现动态代码注入
创建buildSrc模块,这个项目是使用Groovy开发的,需要配置Groovy SDK才可以编译成功。
在这里下载Groovy SDK:[http://groovy-lang.org/download.html](http://groovy-lang.org/download.html),下载之后,配置项目user Library即可。

它里面提供了一个方法,用来向指定类的构造函数注入代码:

```
 /**
     * 植入代码
     * @param buildDir 是项目的build class目录,就是我们需要注入的class所在地
     * @param lib 这个是hackdex的目录,就是AntilazyLoad类的class文件所在地
     */
    public static void process(String buildDir, String lib) {
        println(lib);
        ClassPool classes = ClassPool.getDefault()
        classes.appendClassPath(buildDir)
        classes.appendClassPath(lib)

        // 将需要关联的类的构造方法中插入引用代码
        CtClass c = classes.getCtClass("com.devilwwj.hotfixdemo.BugClass")
        if (c.isFrozen()) {
            c.defrost()
        }
        println("====添加构造方法====")
        def constructor = c.getConstructors()[0];
        constructor.insertBefore("System.out.println(com.devilwwj.hackdex.AntilazyLoad.class);")
        c.writeFile(buildDir)

        CtClass c1 = classes.getCtClass("com.devilwwj.hotfixdemo.LoadBugClass")
        if (c1.isFrozen()) {
            c1.defrost()
        }
        println("====添加构造方法====")
        def constructor1 = c1.getConstructors()[0];
        constructor1.insertBefore("System.out.println(com.devilwwj.hackdex.AntilazyLoad.class);")
        c1.writeFile(buildDir)

    }
```

## 配置app项目的build.gradle

上一小节创建的module提供相应的方法来让我们对项目的类进行代码注入,我们需要在build.gradle来配置让它自动来做这件事:

```
apply plugin: 'com.android.application'

task('processWithJavassist') << {
    String classPath = file('build/intermediates/classes/debug')// 项目编译class所在目录
    com.devilwwj.patch.PatchClass.process(classPath, project(':hackdex').buildDir.absolutePath + "/intermediates/classes/debug") // 第二个参数是hackdex的class所在目录
}

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.devilwwj.hotfixdemo"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        debug {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    applicationVariants.all { variant ->
        variant.dex.dependsOn << processWithJavassist // 在执行dx命令之前将代码打入到class中
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile project(':hotfixlib')
}

```

这时候我们run项目,反编译build/output/apk下的app-debug.apk文件,你就可以看到代码已经成功植入了。

mac下的反编译工具:
[https://sourceforge.net/projects/jadx/?source=typ_redirect](https://sourceforge.net/projects/jadx/?source=typ_redirect)

反编译的结果如下图:

![反编译结果](http://img.blog.csdn.net/20160309174232088)

其实你也可以直接在项目中看:

![代码注入结果](http://img.blog.csdn.net/20160309174352039)

## 创建hotfixlib模块,并关联到项目中

这差不多是最后一步了,也是最核心的一步,提供将heck_dex.jar动态插入到dexElements的方法。

核心代码:
```
package com.devilwwj.hotfixlib;

import android.annotation.TargetApi;
import android.content.Context;

import java.io.File;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

import dalvik.system.DexClassLoader;
import dalvik.system.PathClassLoader;

/**
 * com.devilwwj.hotfixlib
 * Created by devilwwj on 16/3/9.
 */
public final class HotFix {
    public static void patch(Context context, String patchDexFile, String patchClassName) {
        if (patchDexFile != null && new File(patchDexFile).exists()) {
            try {
                if (hasLexClassLoader()) {
                    injectAliyunOs(context, patchDexFile, patchClassName);
                } else if (hasDexClassLoader()) {
                    injectAboveEqualApiLevel14(context, patchDexFile, patchClassName);
                } else {
                    injectBelowApiLevel14(context, patchDexFile, patchClassName);
                }
            } catch (Throwable th) {

            }
        }
    }

    private static boolean hasLexClassLoader() {
        try {
            Class.forName("dalvik.system.LexClassLoader");
            return true;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return false;
        }

    }

    private static boolean hasDexClassLoader() {
        try {
            Class.forName("dalvik.system.BaseDexClassLoader");
            return true;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    private static void injectAliyunOs(Context context, String patchDexFile, String patchClassName) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        PathClassLoader obj = (PathClassLoader) context.getClassLoader();
        String replaceAll = new File(patchDexFile).getName().replaceAll("\\.[a-zA-Z0-9]+", ".lex");
        Class cls = Class.forName("dalvik.system.LexClassLoader");
        Object newInstance = cls.getConstructor(new Class[]{String.class, String.class, String.class, ClassLoader.class}).newInstance(
                new Object[]{context.getDir("dex", 0).getAbsolutePath()
                        + File.separator + replaceAll, context.getDir("dex", 0).getAbsolutePath(), patchDexFile, obj});
        cls.getMethod("loadClass", new Class[]{String.class}).invoke(newInstance, new Object[]{patchClassName});
        setField(obj, PathClassLoader.class, "mPaths", appendArray(getField(obj, PathClassLoader.class, "mPaths"), getField(newInstance, cls, "mRawDexPath")));
        setField(obj, PathClassLoader.class, "mFiles", combineArray(getField(obj, PathClassLoader.class, "mFiles"), getField(newInstance, cls, "mFiles")));
        setField(obj, PathClassLoader.class, "mZips", combineArray(getField(obj, PathClassLoader.class, "mZips"), getField(newInstance, cls, "mZips")));
        setField(obj, PathClassLoader.class, "mLexs", combineArray(getField(obj, PathClassLoader.class, "mLexs"), getField(newInstance, cls, "mDexs")));
    }

    @TargetApi(14)
    private static void injectBelowApiLevel14(Context context, String str, String str2) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        PathClassLoader obj = (PathClassLoader) context.getClassLoader();
        DexClassLoader dexClassLoader = new DexClassLoader(str, context.getDir("dex", 0).getAbsolutePath(), str, context.getClassLoader());
        dexClassLoader.loadClass(str2);
        setField(obj, PathClassLoader.class, "mPaths",
                appendArray(getField(obj, PathClassLoader.class, "mPaths"), getField(dexClassLoader, DexClassLoader.class, "mRawDexPath")));
        setField(obj, PathClassLoader.class, "mFiles",
                combineArray(getField(obj, PathClassLoader.class, "mFiles"), getField(dexClassLoader, DexClassLoader.class, "mFiles")));
        setField(obj, PathClassLoader.class, "mZips",
                combineArray(getField(obj, PathClassLoader.class, "mZips"), getField(dexClassLoader, DexClassLoader.class, "mZips")));
        setField(obj, PathClassLoader.class, "mDexs",
                combineArray(getField(obj, PathClassLoader.class, "mDexs"), getField(dexClassLoader, DexClassLoader.class, "mDexs")));
        obj.loadClass(str2);
    }

    /**
     * 将dex注入dexElements数组中
     * @param context
     * @param str
     * @param str2
     * @throws ClassNotFoundException
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    private static void injectAboveEqualApiLevel14(Context context, String str, String str2) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        PathClassLoader pathClassLoader = (PathClassLoader) context.getClassLoader();
        Object a = combineArray(getDexElements(getPathList(pathClassLoader)), getDexElements(getPathList(new DexClassLoader(str, context.getDir("dex", 0).getAbsolutePath(), str, context.getClassLoader()))));
        Object a2 = getPathList(pathClassLoader);
        setField(a2, a2.getClass(), "dexElements", a);
        pathClassLoader.loadClass(str2);
    }

    /**
     * 通过PathClassLoader拿到pathList
     * @param obj
     * @return
     * @throws ClassNotFoundException
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    private static Object getPathList(Object obj) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        return getField(obj, Class.forName("dalvik.system.BaseDexClassLoader"), "pathList");
    }

    /**
     * 通过pathList取得dexElements对象
     * @param obj
     * @return
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    private static Object getDexElements(Object obj) throws NoSuchFieldException, IllegalAccessException {
        return getField(obj, obj.getClass(), "dexElements");
    }

    /**
     * 通过反射拿到指定对象
     * @param obj
     * @param cls
     * @param str
     * @return
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    private static Object getField(Object obj, Class cls, String str) throws NoSuchFieldException, IllegalAccessException {
        Field declaredField = cls.getDeclaredField(str);
        declaredField.setAccessible(true);
        return declaredField.get(obj);
    }

    /**
     * 通过反射设置属性
     * @param obj
     * @param cls
     * @param str
     * @param obj2
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    private static void setField(Object obj, Class cls, String str, Object obj2) throws NoSuchFieldException, IllegalAccessException {
        Field declaredField = cls.getDeclaredField(str);
        declaredField.setAccessible(true);
        declaredField.set(obj, obj2);
    }

    /**
     * 合并数组
     * @param obj
     * @param obj2
     * @return
     */
    private static Object combineArray(Object obj, Object obj2) {
        Class componentType = obj2.getClass().getComponentType();
        int length = Array.getLength(obj2);
        int length2 = Array.getLength(obj) + length;
        Object newInstance = Array.newInstance(componentType, length2);
        for (int i = 0; i < length2; i++) {
            if (i < length) {
                Array.set(newInstance, i, Array.get(obj2, i));
            } else {
                Array.set(newInstance, i, Array.get(obj, i - length));
            }
        }
        return newInstance;
    }

    /**
     * 添加到数组
     * @param obj
     * @param obj2
     * @return
     */
    private static Object appendArray(Object obj, Object obj2) {
        Class componentType = obj.getClass().getComponentType();
        int length = Array.getLength(obj);
        Object newInstance = Array.newInstance(componentType, length + 1);
        Array.set(newInstance, 0, obj2);
        for (int i = 0; i < length + 1; i++) {
            Array.set(newInstance, i, Array.get(obj, i - 1));
        }
        return newInstance;
    }
}

```

## 准备补丁,最后测试结果

补丁是我们程序修复bug的包,如果我们已经上线的包出现了bug,你需要紧急修复,那你就找到有bug的那个类,将它修复,然后将这个修复的class文件打包成jar包,让服务端将这个补丁包放到指定位置,你的就程序就可以将这补丁包下载到sdcard,之后就是程序自动帮你打补丁把问题修复。

比如我们上面提到的BugClass:
未修复之前:

```
public class BugClass {

    public String bug() {
        return "bug class";
    }
}
```

修复之后:

```
public class BugClass {

    public String bug() {
        return "小巫将bug修复啦!!!";
    }
}

```

你要做的就是替换这个类,怎么做?

先打包:

![打包命令](http://img.blog.csdn.net/20160310125151109)

*记住:一定要经过dx工具转化,然后路径一定要对*

patch_dex.jar就是我们的补丁包,这里我们为了演示把它放到项目的assets目录下:

![补丁包](http://img.blog.csdn.net/20160310125453204)

之后,就是测试效果了,看动态图:

![打补丁过程](http://img.blog.csdn.net/20160310130014523)

好,到这里就大公告成了,我们的bug被修复了啦。

# 总结
本次实践过程是基于HotFix框架,在这里感谢开源的作者,因为不满足于拿作者的东西直接用,然后不知道为什么,所以笔者把整个过程都跑了一遍,正所谓实践出真知,原本以为很难的东西通过反复实践也会变得不那么难,期间实践自然不会那么顺利,笔者就遇到一个坑,比如Groovy编译,hack_dex包中的类找不到等等,但最后都一一解决了,研究完这个热更新框架,再去研究其他热更新框架也是一样的,因为原理都一样,所以就不纠结研究哪个了,之后笔者也会把这个技术用到项目中去,不用每次发包也是心情愉悦的,最后感谢各位看官耐心看,有啥问题就直接留言吧。

> 参考:
> http://blog.csdn.net/lmj623565791/article/details/49883661
> http://www.jianshu.com/p/56facb3732a7

![1元表真心](http://img.blog.csdn.net/20160310131859376)


text:
Frappe bundles the c3.js libary to make charts inside the app and provides a wrapper class so that you can start using charts out of the box. To use chart, you need the x and y data, make a wrapper block and then just make the chart object.

### Time Series Example

		page.chart = new frappe.ui.Chart({
			// attach the chart here
			wrapper: $('<div>').appendTo(page.body),

			// pass the data, like
			// ['x', '2016-01-01', '2016-01-02']
			// ['Value', 20, 30]
			data: {
				x: 'x',
				xFormat: '%Y-%m-%d',
				columns: [data[0], data[1]],
			},
			legend: {
				show: false
			},
			axis: {
				x: {
					type: 'timeseries',
				},
				y: {
					min: 0,
					padding: {bottom: 10}
				}
			}
		});

### Help

For more options, see the [c3js.org](http://c3js.org/examples.html) docs


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    style="@style/iah_listView_childBackgroundStyle">

    <TextView
        android:id="@+id/sectionlisttextview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/iah_listView_childTextStyle"
        android:text="" />

</LinearLayout>